1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2004 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>
29 #include "inspircd_io.h"
30 #include "inspircd_util.h"
31 #include "inspstring.h"
32 #include "helperfuncs.h"
34 extern ServerConfig *Config;
35 extern int boundPortCount;
36 extern int openSockfd[MAXSOCKS];
38 std::vector<std::string> include_stack;
40 ServerConfig::ServerConfig()
42 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
43 *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
44 *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
45 *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
51 NetBufferSize = 10240;
52 SoftLimit = MAXCLIENTS;
61 void ServerConfig::Read(bool bail, userrec* user)
63 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
64 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
66 std::stringstream errstr;
67 include_stack.clear();
69 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
72 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
75 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
83 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
86 errstr.getline(dataline,1024);
87 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
92 WriteOpers("There were errors in the configuration file:");
95 errstr.getline(dataline,1024);
103 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
104 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
105 ConfValue("server","network",0,Config->Network,&Config->config_f);
106 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
107 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
108 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
109 ConfValue("files","motd",0,Config->motd,&Config->config_f);
110 ConfValue("files","rules",0,Config->rules,&Config->config_f);
111 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
112 ConfValue("power","pause",0,pauseval,&Config->config_f);
113 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
114 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
115 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
116 ConfValue("options","loglevel",0,dbg,&Config->config_f);
117 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
118 ConfValue("options","maxwho",0,MW,&Config->config_f);
119 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
120 ConfValue("options","allowprotect",0,AP,&Config->config_f);
121 ConfValue("options","allowfounder",0,AF,&Config->config_f);
122 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
123 ConfValue("dns","timeout",0,DNT,&Config->config_f);
124 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
125 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
126 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
127 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
129 Config->SoftLimit = atoi(SLIMT);
130 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
132 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
133 Config->SoftLimit = MAXCLIENTS;
135 Config->MaxConn = atoi(MCON);
136 if (Config->MaxConn > SOMAXCONN)
137 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
138 Config->NetBufferSize = atoi(NB);
139 Config->MaxWhoResults = atoi(MW);
140 Config->dns_timeout = atoi(DNT);
141 if (!Config->dns_timeout)
142 Config->dns_timeout = 5;
143 if (!Config->MaxConn)
144 Config->MaxConn = SOMAXCONN;
145 if (!*Config->DNSServer)
146 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
147 if (!*Config->ModPath)
148 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
149 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
150 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
152 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
153 Config->NetBufferSize = 10240;
155 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
157 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
158 Config->MaxWhoResults = 128;
160 Config->LogLevel = DEFAULT;
161 if (!strcmp(dbg,"debug"))
163 Config->LogLevel = DEBUG;
164 Config->debugging = 1;
166 if (!strcmp(dbg,"verbose"))
167 Config->LogLevel = VERBOSE;
168 if (!strcmp(dbg,"default"))
169 Config->LogLevel = DEFAULT;
170 if (!strcmp(dbg,"sparse"))
171 Config->LogLevel = SPARSE;
172 if (!strcmp(dbg,"none"))
173 Config->LogLevel = NONE;
175 readfile(Config->MOTD,Config->motd);
176 log(DEFAULT,"Reading message of the day...");
177 readfile(Config->RULES,Config->rules);
178 log(DEFAULT,"Reading connect classes...");
180 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
183 ConfValue("connect","allow",i,Value,&Config->config_f);
184 ConfValue("connect","timeout",i,timeout,&Config->config_f);
185 ConfValue("connect","flood",i,flood,&Config->config_f);
186 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
187 ConfValue("connect","threshold",i,thold,&Config->config_f);
188 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
189 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
192 strlcpy(c.host,Value,MAXBUF);
194 strlcpy(Value,"",MAXBUF);
195 ConfValue("connect","password",i,Value,&Config->config_f);
196 strlcpy(c.pass,Value,MAXBUF);
197 c.registration_timeout = 90; // default is 2 minutes
199 c.flood = atoi(flood);
201 c.sendqmax = 262144; // 256k
202 c.recvqmax = 4096; // 4k
205 c.threshold = atoi(thold);
209 c.sendqmax = atoi(sqmax);
213 c.recvqmax = atoi(rqmax);
217 c.registration_timeout = atoi(timeout);
221 c.pingtime = atoi(pfreq);
223 Classes.push_back(c);
227 ConfValue("connect","deny",i,Value,&Config->config_f);
228 strlcpy(c.host,Value,MAXBUF);
230 Classes.push_back(c);
231 log(DEBUG,"Read connect class type DENY, host=%s",c.host);
235 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
236 read_xline_defaults();
237 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
238 apply_lines(APPLY_ALL);
240 ConfValue("pid","file",0,Config->PID,&Config->config_f);
241 // write once here, to try it out and make sure its ok
242 WritePID(Config->PID);
244 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
247 log(DEFAULT,"Adding and removing modules due to rehash...");
249 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
251 // store the old module names
252 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
254 old_module_names.push_back(*t);
257 // get the new module names
258 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
260 ConfValue("module","name",count2,Value,&Config->config_f);
261 new_module_names.push_back(Value);
264 // now create a list of new modules that are due to be loaded
265 // and a seperate list of modules which are due to be unloaded
266 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
269 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
275 added_modules.push_back(*_new);
277 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
280 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
286 removed_modules.push_back(*oldm);
288 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
290 int rem = 0, add = 0;
291 if (!removed_modules.empty())
292 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
294 if (UnloadModule(removing->c_str()))
296 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
297 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
302 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
305 if (!added_modules.empty())
306 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
308 if (LoadModule(adding->c_str()))
310 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
311 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
316 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
319 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
320 (unsigned long)add,(unsigned long)added_modules.size());
325 void WriteOpers(char* text, ...);
327 void Exit (int status)
329 if (Config->log_file)
330 fclose(Config->log_file);
331 send_error("Server shutdown.");
335 void Killed(int status)
337 if (Config->log_file)
338 fclose(Config->log_file);
339 send_error("Server terminated.");
343 void Rehash(int status)
345 WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
346 Config->Read(false,NULL);
353 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
354 printf("(C) ChatSpike Development team.\033[0m\n\n");
355 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
356 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
357 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
358 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
361 void WritePID(std::string filename)
363 ofstream outfile(filename.c_str());
364 if (outfile.is_open())
371 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
372 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
378 int DaemonSeed (void)
381 signal (SIGALRM, SIG_IGN);
382 signal (SIGHUP, Rehash);
383 signal (SIGPIPE, SIG_IGN);
384 signal (SIGTERM, Exit);
385 signal (SIGSEGV, Error);
386 if ((childpid = fork ()) < 0)
388 else if (childpid > 0)
392 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
394 setpriority(PRIO_PROCESS,(int)getpid(),15);
396 if (Config->unlimitcore)
399 if (getrlimit(RLIMIT_CORE, &rl) == -1)
401 log(DEFAULT,"Failed to getrlimit()!");
406 rl.rlim_cur = rl.rlim_max;
407 if (setrlimit(RLIMIT_CORE, &rl) == -1)
408 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
416 /* Make Sure Modules Are Avaliable!
417 * (BugFix By Craig.. See? I do work! :p)
418 * Modified by brain, requires const char*
419 * to work with other API functions
422 bool FileExists (const char* file)
425 if ((input = fopen (file, "r")) == NULL)
436 /* ConfProcess does the following things to a config line in the following order:
438 * Processes the line for syntax errors as shown below
439 * (1) Line void of quotes or equals (a malformed, illegal tag format)
440 * (2) Odd number of quotes on the line indicating a missing quote
441 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
442 * (4) Spaces between the opening bracket (<) and the keyword
443 * (5) Spaces between a keyword and an equals sign
444 * (6) Spaces between an equals sign and a quote
445 * Removes trailing spaces
446 * Removes leading spaces
447 * Converts tabs to spaces
448 * Turns multiple spaces that are outside of quotes into single spaces
451 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
453 long number_of_quotes = 0;
454 long number_of_equals = 0;
455 bool has_open_bracket = false;
456 bool in_quotes = false;
462 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
463 for (unsigned int d = 0; d < strlen(buffer); d++)
464 if ((buffer[d]) == 9)
466 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
467 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
469 // empty lines are syntactically valid, as are comments
470 if (!(*buffer) || buffer[0] == '#')
473 for (unsigned int c = 0; c < strlen(buffer); c++)
475 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
476 // search and replace later :)
477 if ((!in_quotes) && (buffer[c] == ' '))
479 if ((buffer[c] == '<') && (!in_quotes))
481 has_open_bracket = true;
482 if (strlen(buffer) == 1)
484 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
488 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
490 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
495 if (buffer[c] == '"')
498 in_quotes = (!in_quotes);
500 if ((buffer[c] == '=') && (!in_quotes))
503 if (strlen(buffer) == c)
505 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
509 else if (buffer[c+1] != '"')
511 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
517 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
521 else if (buffer[c-1] == '\xA0')
523 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
529 // no quotes, and no equals. something freaky.
530 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
532 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
536 // odd number of quotes. thats just wrong.
537 if ((number_of_quotes % 2) != 0)
539 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
543 if (number_of_equals < (number_of_quotes/2))
545 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
547 if (number_of_equals > (number_of_quotes/2))
549 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
552 std::string parsedata = buffer;
553 // turn multispace into single space
554 while (parsedata.find("\xA0\xA0") != std::string::npos)
556 parsedata.erase(parsedata.find("\xA0\xA0"),1);
559 // turn our hardspace back into softspace
560 for (unsigned int d = 0; d < parsedata.length(); d++)
562 if (parsedata[d] == '\xA0')
566 // and we're done, the line is fine!
570 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
573 unsigned int bufptr = 0;
574 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
576 c_read = fgetc(file);
577 if ((c_read != '\n') && (c_read != '\r'))
578 buffer[bufptr++] = c_read;
580 buffer[bufptr] = '\0';
584 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
587 errorstream->str("");
589 // first, check that the file exists before we try to do anything with it
590 if (!FileExists(filename))
592 *errorstream << "File " << filename << " not found." << endl;
595 // Fix the chmod of the file to restrict it to the current user and group
596 chmod(filename,0600);
597 for (unsigned int t = 0; t < include_stack.size(); t++)
599 if (std::string(filename) == include_stack[t])
601 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
605 include_stack.push_back(filename);
607 FILE* conf = fopen(filename,"r");
613 if (fgets_safe(buffer, MAXBUF, conf))
615 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
617 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
619 if (!strncmp(buffer,"<include file=\"",15))
622 char confpath[10240],newconf[10240];
623 // include file directive
624 buf += 15; // advance to filename
625 for (unsigned int j = 0; j < strlen(buf); j++)
635 log(DEFAULT,"Opening included file '%s'",buf);
638 strlcpy(confpath,CONFIG_FILE,10240);
639 if (strstr(confpath,"/inspircd.conf"))
641 // leaves us with just the path
642 *(strstr(confpath,"/inspircd.conf")) = '\0';
644 snprintf(newconf,10240,"%s/%s",confpath,buf);
646 else snprintf(newconf,10240,"%s",buf);
647 std::stringstream merge(stringstream::in | stringstream::out);
648 // recursively call LoadConf and get the new data, use the same errorstream
649 if (LoadConf(newconf, &merge, errorstream))
651 // append to the end of the file
652 std::string newstuff = merge.str();
657 // the error propogates up to its parent recursively
658 // causing the config reader to bail at the top level.
666 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
684 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
686 int EnumConf(std::stringstream *config, const char* tag)
689 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
690 int in_token, in_quotes, tptr, idx = 0;
692 const char* buf = config->str().c_str();
694 long len = strlen(buf);
704 if ((c == '#') && (lastc == '\n'))
706 while ((c != '\n') && (bptr<len))
712 if ((c == '<') && (!in_quotes))
727 in_quotes = (!in_quotes);
729 if ((c == '>') && (!in_quotes))
732 if (!strcmp(c_tag,tag))
734 /* correct tag, but wrong index */
744 if ((in_token) && (c != '\n') && (c != '\r'))
754 /* Counts the number of values within a certain tag */
756 int EnumValues(std::stringstream *config, const char* tag, int index)
759 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
760 int in_token, in_quotes, tptr, idx = 0;
762 bool correct_tag = false;
765 const char* buf = config->str().c_str();
767 long len = strlen(buf);
777 if ((c == '#') && (lastc == '\n'))
779 while ((c != '\n') && (bptr<len))
785 if ((c == '<') && (!in_quotes))
796 if ((!strcmp(c_tag,tag)) && (idx == index))
805 in_quotes = (!in_quotes);
808 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
812 if ((c == '>') && (!in_quotes))
817 if (!strcmp(c_tag,tag))
819 /* correct tag, but wrong index */
829 if ((in_token) && (c != '\n') && (c != '\r'))
841 int ConfValueEnum(char* tag, std::stringstream* config)
843 return EnumConf(config,tag);
848 /* Retrieves a value from the config file. If there is more than one value of the specified
849 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
851 * ConfValue("oper","name",2,result);
854 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
857 char buffer[65535], c_tag[MAXBUF], c, lastc;
858 int in_token, in_quotes, tptr, idx = 0;
861 const char* buf = config->str().c_str();
863 long len = config->str().length();
875 // FIX: Treat tabs as spaces
878 if ((c == '<') && (!in_quotes))
889 // FIX: Tab can follow a tagname as well as space.
890 } while ((c != ' ') && (c != 9));
894 in_quotes = (!in_quotes);
896 if ((c == '>') && (!in_quotes))
901 if (!strcmp(c_tag,tag))
903 if ((buffer) && (c_tag) && (var))
905 key = strstr(buffer,var);
908 /* value not found in tag */
926 for (unsigned j = 0; j < strlen(key); j++)
933 strlcpy(result,key,MAXBUF);
939 if (!strcmp(c_tag,tag))
941 /* correct tag, but wrong index */
951 if ((in_token) && (c != '\n') && (c != '\r'))
958 strcpy(result,""); // value or its tag not found at all
964 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
966 ReadConf(config, tag, var, index, result);
972 // This will bind a socket to a port. It works for UDP/TCP
973 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
975 memset((char *)&server,0,sizeof(server));
977 inet_aton(addr,&addy);
978 server.sin_family = AF_INET;
979 if (!strcmp(addr,""))
981 server.sin_addr.s_addr = htonl(INADDR_ANY);
985 server.sin_addr = addy;
987 server.sin_port = htons(port);
988 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
994 listen(sockfd, Config->MaxConn);
1000 // Open a TCP Socket
1001 int OpenTCPSocket (void)
1005 struct linger linger = { 0 };
1007 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1011 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1012 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1014 linger.l_linger = 1;
1015 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));