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 void WriteOpers(char* text, ...);
42 void Exit (int status)
45 fclose(Config->log_file);
46 send_error("Server shutdown.");
50 void Killed(int status)
53 fclose(Config->log_file);
54 send_error("Server terminated.");
58 void Rehash(int status)
60 WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
61 ReadConfig(false,NULL);
68 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
69 printf("(C) ChatSpike Development team.\033[0m\n\n");
70 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
71 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
72 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
73 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
76 void WritePID(std::string filename)
78 ofstream outfile(filename.c_str());
79 if (outfile.is_open())
86 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
87 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
96 signal (SIGALRM, SIG_IGN);
97 signal (SIGHUP, Rehash);
98 signal (SIGPIPE, SIG_IGN);
99 signal (SIGTERM, Exit);
100 signal (SIGSEGV, Error);
101 if ((childpid = fork ()) < 0)
103 else if (childpid > 0)
107 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
109 setpriority(PRIO_PROCESS,(int)getpid(),15);
111 if (Config->unlimitcore)
114 if (getrlimit(RLIMIT_CORE, &rl) == -1)
116 log(DEFAULT,"Failed to getrlimit()!");
121 rl.rlim_cur = rl.rlim_max;
122 if (setrlimit(RLIMIT_CORE, &rl) == -1)
123 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
131 /* Make Sure Modules Are Avaliable!
132 * (BugFix By Craig.. See? I do work! :p)
133 * Modified by brain, requires const char*
134 * to work with other API functions
137 bool FileExists (const char* file)
140 if ((input = fopen (file, "r")) == NULL)
151 /* ConfProcess does the following things to a config line in the following order:
153 * Processes the line for syntax errors as shown below
154 * (1) Line void of quotes or equals (a malformed, illegal tag format)
155 * (2) Odd number of quotes on the line indicating a missing quote
156 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
157 * (4) Spaces between the opening bracket (<) and the keyword
158 * (5) Spaces between a keyword and an equals sign
159 * (6) Spaces between an equals sign and a quote
160 * Removes trailing spaces
161 * Removes leading spaces
162 * Converts tabs to spaces
163 * Turns multiple spaces that are outside of quotes into single spaces
166 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
168 long number_of_quotes = 0;
169 long number_of_equals = 0;
170 bool has_open_bracket = false;
171 bool in_quotes = false;
177 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
178 for (unsigned int d = 0; d < strlen(buffer); d++)
179 if ((buffer[d]) == 9)
181 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
182 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
184 // empty lines are syntactically valid, as are comments
185 if (!(*buffer) || buffer[0] == '#')
188 for (unsigned int c = 0; c < strlen(buffer); c++)
190 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
191 // search and replace later :)
192 if ((!in_quotes) && (buffer[c] == ' '))
194 if ((buffer[c] == '<') && (!in_quotes))
196 has_open_bracket = true;
197 if (strlen(buffer) == 1)
199 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
203 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
205 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
210 if (buffer[c] == '"')
213 in_quotes = (!in_quotes);
215 if ((buffer[c] == '=') && (!in_quotes))
218 if (strlen(buffer) == c)
220 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
224 else if (buffer[c+1] != '"')
226 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
232 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
236 else if (buffer[c-1] == '\xA0')
238 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
244 // no quotes, and no equals. something freaky.
245 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
247 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
251 // odd number of quotes. thats just wrong.
252 if ((number_of_quotes % 2) != 0)
254 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
258 if (number_of_equals < (number_of_quotes/2))
260 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
262 if (number_of_equals > (number_of_quotes/2))
264 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
267 std::string parsedata = buffer;
268 // turn multispace into single space
269 while (parsedata.find("\xA0\xA0") != std::string::npos)
271 parsedata.erase(parsedata.find("\xA0\xA0"),1);
274 // turn our hardspace back into softspace
275 for (unsigned int d = 0; d < parsedata.length(); d++)
277 if (parsedata[d] == '\xA0')
281 // and we're done, the line is fine!
285 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
288 unsigned int bufptr = 0;
289 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
291 c_read = fgetc(file);
292 if ((c_read != '\n') && (c_read != '\r'))
293 buffer[bufptr++] = c_read;
295 buffer[bufptr] = '\0';
299 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
302 errorstream->str("");
304 // first, check that the file exists before we try to do anything with it
305 if (!FileExists(filename))
307 *errorstream << "File " << filename << " not found." << endl;
310 // Fix the chmod of the file to restrict it to the current user and group
311 chmod(filename,0600);
312 for (unsigned int t = 0; t < include_stack.size(); t++)
314 if (std::string(filename) == include_stack[t])
316 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
320 include_stack.push_back(filename);
322 FILE* conf = fopen(filename,"r");
328 if (fgets_safe(buffer, MAXBUF, conf))
330 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
332 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
334 if (!strncmp(buffer,"<include file=\"",15))
337 char confpath[10240],newconf[10240];
338 // include file directive
339 buf += 15; // advance to filename
340 for (unsigned int j = 0; j < strlen(buf); j++)
350 log(DEFAULT,"Opening included file '%s'",buf);
353 strlcpy(confpath,CONFIG_FILE,10240);
354 if (strstr(confpath,"/inspircd.conf"))
356 // leaves us with just the path
357 *(strstr(confpath,"/inspircd.conf")) = '\0';
359 snprintf(newconf,10240,"%s/%s",confpath,buf);
361 else snprintf(newconf,10240,"%s",buf);
362 std::stringstream merge(stringstream::in | stringstream::out);
363 // recursively call LoadConf and get the new data, use the same errorstream
364 if (LoadConf(newconf, &merge, errorstream))
366 // append to the end of the file
367 std::string newstuff = merge.str();
372 // the error propogates up to its parent recursively
373 // causing the config reader to bail at the top level.
381 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
399 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
401 int EnumConf(std::stringstream *config, const char* tag)
404 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
405 int in_token, in_quotes, tptr, idx = 0;
407 const char* buf = config->str().c_str();
409 long len = strlen(buf);
419 if ((c == '#') && (lastc == '\n'))
421 while ((c != '\n') && (bptr<len))
427 if ((c == '<') && (!in_quotes))
442 in_quotes = (!in_quotes);
444 if ((c == '>') && (!in_quotes))
447 if (!strcmp(c_tag,tag))
449 /* correct tag, but wrong index */
459 if ((in_token) && (c != '\n') && (c != '\r'))
469 /* Counts the number of values within a certain tag */
471 int EnumValues(std::stringstream *config, const char* tag, int index)
474 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
475 int in_token, in_quotes, tptr, idx = 0;
477 bool correct_tag = false;
480 const char* buf = config->str().c_str();
482 long len = strlen(buf);
492 if ((c == '#') && (lastc == '\n'))
494 while ((c != '\n') && (bptr<len))
500 if ((c == '<') && (!in_quotes))
511 if ((!strcmp(c_tag,tag)) && (idx == index))
520 in_quotes = (!in_quotes);
523 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
527 if ((c == '>') && (!in_quotes))
532 if (!strcmp(c_tag,tag))
534 /* correct tag, but wrong index */
544 if ((in_token) && (c != '\n') && (c != '\r'))
556 int ConfValueEnum(char* tag, std::stringstream* config)
558 return EnumConf(config,tag);
563 /* Retrieves a value from the config file. If there is more than one value of the specified
564 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
566 * ConfValue("oper","name",2,result);
569 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
572 char buffer[65535], c_tag[MAXBUF], c, lastc;
573 int in_token, in_quotes, tptr, idx = 0;
576 const char* buf = config->str().c_str();
578 long len = config->str().length();
590 // FIX: Treat tabs as spaces
593 if ((c == '<') && (!in_quotes))
604 // FIX: Tab can follow a tagname as well as space.
605 } while ((c != ' ') && (c != 9));
609 in_quotes = (!in_quotes);
611 if ((c == '>') && (!in_quotes))
616 if (!strcmp(c_tag,tag))
618 if ((buffer) && (c_tag) && (var))
620 key = strstr(buffer,var);
623 /* value not found in tag */
641 for (unsigned j = 0; j < strlen(key); j++)
648 strlcpy(result,key,MAXBUF);
654 if (!strcmp(c_tag,tag))
656 /* correct tag, but wrong index */
666 if ((in_token) && (c != '\n') && (c != '\r'))
673 strcpy(result,""); // value or its tag not found at all
679 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
681 ReadConf(config, tag, var, index, result);
687 // This will bind a socket to a port. It works for UDP/TCP
688 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
690 memset((char *)&server,0,sizeof(server));
692 inet_aton(addr,&addy);
693 server.sin_family = AF_INET;
694 if (!strcmp(addr,""))
696 server.sin_addr.s_addr = htonl(INADDR_ANY);
700 server.sin_addr = addy;
702 server.sin_port = htons(port);
703 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
709 listen(sockfd, Config->MaxConn);
716 int OpenTCPSocket (void)
720 struct linger linger = { 0 };
722 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
726 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
727 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
730 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));