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 FILE *log_file;
35 extern int boundPortCount;
36 extern int openSockfd[MAXSOCKS];
38 extern bool unlimitcore;
40 std::vector<std::string> include_stack;
42 void WriteOpers(char* text, ...);
44 void Exit (int status)
48 send_error("Server shutdown.");
52 void Killed(int status)
56 send_error("Server terminated.");
60 void Rehash(int status)
62 WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
63 ReadConfig(false,NULL);
70 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
71 printf("(C) ChatSpike Development team.\033[0m\n\n");
72 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
73 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
74 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
75 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
78 void WritePID(std::string filename)
80 ofstream outfile(filename.c_str());
81 if (outfile.is_open())
88 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
89 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
98 signal (SIGALRM, SIG_IGN);
99 signal (SIGHUP, Rehash);
100 signal (SIGPIPE, SIG_IGN);
101 signal (SIGTERM, Exit);
102 signal (SIGSEGV, Error);
103 if ((childpid = fork ()) < 0)
105 else if (childpid > 0)
109 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
110 freopen("/dev/null","w",stdout);
111 freopen("/dev/null","w",stderr);
113 setpriority(PRIO_PROCESS,(int)getpid(),15);
118 if (getrlimit(RLIMIT_CORE, &rl) == -1)
120 log(DEFAULT,"Failed to getrlimit()!");
125 rl.rlim_cur = rl.rlim_max;
126 if (setrlimit(RLIMIT_CORE, &rl) == -1)
127 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
135 /* Make Sure Modules Are Avaliable!
136 * (BugFix By Craig.. See? I do work! :p)
137 * Modified by brain, requires const char*
138 * to work with other API functions
141 bool FileExists (const char* file)
144 if ((input = fopen (file, "r")) == NULL)
155 /* ConfProcess does the following things to a config line in the following order:
157 * Processes the line for syntax errors as shown below
158 * (1) Line void of quotes or equals (a malformed, illegal tag format)
159 * (2) Odd number of quotes on the line indicating a missing quote
160 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
161 * (4) Spaces between the opening bracket (<) and the keyword
162 * (5) Spaces between a keyword and an equals sign
163 * (6) Spaces between an equals sign and a quote
164 * Removes trailing spaces
165 * Removes leading spaces
166 * Converts tabs to spaces
167 * Turns multiple spaces that are outside of quotes into single spaces
170 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
172 long number_of_quotes = 0;
173 long number_of_equals = 0;
174 bool has_open_bracket = false;
175 bool in_quotes = false;
181 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
182 for (unsigned int d = 0; d < strlen(buffer); d++)
183 if ((buffer[d]) == 9)
185 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
186 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
188 // empty lines are syntactically valid, as are comments
189 if (!(*buffer) || buffer[0] == '#')
192 for (unsigned int c = 0; c < strlen(buffer); c++)
194 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
195 // search and replace later :)
196 if ((!in_quotes) && (buffer[c] == ' '))
198 if ((buffer[c] == '<') && (!in_quotes))
200 has_open_bracket = true;
201 if (strlen(buffer) == 1)
203 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
207 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
209 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
214 if (buffer[c] == '"')
217 in_quotes = (!in_quotes);
219 if ((buffer[c] == '=') && (!in_quotes))
222 if (strlen(buffer) == c)
224 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
228 else if (buffer[c+1] != '"')
230 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
236 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
240 else if (buffer[c-1] == '\xA0')
242 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
248 // no quotes, and no equals. something freaky.
249 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
251 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
255 // odd number of quotes. thats just wrong.
256 if ((number_of_quotes % 2) != 0)
258 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
262 if (number_of_equals < (number_of_quotes/2))
264 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
266 if (number_of_equals > (number_of_quotes/2))
268 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
271 std::string parsedata = buffer;
272 // turn multispace into single space
273 while (parsedata.find("\xA0\xA0") != std::string::npos)
275 parsedata.erase(parsedata.find("\xA0\xA0"),1);
278 // turn our hardspace back into softspace
279 for (unsigned int d = 0; d < parsedata.length(); d++)
281 if (parsedata[d] == '\xA0')
285 // and we're done, the line is fine!
289 /* A special version of fgets that will read \r, \n, \r\n or even \n\r, it doesnt care :-) */
291 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
294 unsigned int bufptr = 0;
295 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
297 c_read = fgetc(file);
298 if ((c_read != '\n') && (c_read != '\r'))
299 buffer[bufptr++] = c_read;
301 buffer[bufptr] = '\0';
305 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
308 errorstream->str("");
310 // first, check that the file exists before we try to do anything with it
311 if (!FileExists(filename))
313 *errorstream << "File " << filename << " not found." << endl;
316 // Fix the chmod of the file to restrict it to the current user and group
317 chmod(filename,0600);
318 for (unsigned int t = 0; t < include_stack.size(); t++)
320 if (std::string(filename) == include_stack[t])
322 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
326 include_stack.push_back(filename);
328 FILE* conf = fopen(filename,"r");
334 if (fgets_safe(buffer, MAXBUF, conf))
336 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
338 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
340 if (!strncmp(buffer,"<include file=\"",15))
343 char confpath[10240],newconf[10240];
344 // include file directive
345 buf += 15; // advance to filename
346 for (unsigned int j = 0; j < strlen(buf); j++)
356 log(DEFAULT,"Opening included file '%s'",buf);
359 strlcpy(confpath,CONFIG_FILE,10240);
360 if (strstr(confpath,"/inspircd.conf"))
362 // leaves us with just the path
363 *(strstr(confpath,"/inspircd.conf")) = '\0';
365 snprintf(newconf,10240,"%s/%s",confpath,buf);
367 else snprintf(newconf,10240,"%s",buf);
368 std::stringstream merge(stringstream::in | stringstream::out);
369 // recursively call LoadConf and get the new data, use the same errorstream
370 if (LoadConf(newconf, &merge, errorstream))
372 // append to the end of the file
373 std::string newstuff = merge.str();
378 // the error propogates up to its parent recursively
379 // causing the config reader to bail at the top level.
387 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
402 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
415 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
417 int EnumConf(std::stringstream *config, const char* tag)
420 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
421 int in_token, in_quotes, tptr, idx = 0;
423 const char* buf = config->str().c_str();
425 long len = strlen(buf);
435 if ((c == '#') && (lastc == '\n'))
437 while ((c != '\n') && (bptr<len))
443 if ((c == '<') && (!in_quotes))
458 in_quotes = (!in_quotes);
460 if ((c == '>') && (!in_quotes))
463 if (!strcmp(c_tag,tag))
465 /* correct tag, but wrong index */
475 if ((in_token) && (c != '\n') && (c != '\r'))
485 /* Counts the number of values within a certain tag */
487 int EnumValues(std::stringstream *config, const char* tag, int index)
490 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
491 int in_token, in_quotes, tptr, idx = 0;
493 bool correct_tag = false;
496 const char* buf = config->str().c_str();
498 long len = strlen(buf);
508 if ((c == '#') && (lastc == '\n'))
510 while ((c != '\n') && (bptr<len))
516 if ((c == '<') && (!in_quotes))
527 if ((!strcmp(c_tag,tag)) && (idx == index))
536 in_quotes = (!in_quotes);
539 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
543 if ((c == '>') && (!in_quotes))
548 if (!strcmp(c_tag,tag))
550 /* correct tag, but wrong index */
560 if ((in_token) && (c != '\n') && (c != '\r'))
572 int ConfValueEnum(char* tag, std::stringstream* config)
574 return EnumConf(config,tag);
579 /* Retrieves a value from the config file. If there is more than one value of the specified
580 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
582 * ConfValue("oper","name",2,result);
585 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
588 char buffer[65535], c_tag[MAXBUF], c, lastc;
589 int in_token, in_quotes, tptr, idx = 0;
592 const char* buf = config->str().c_str();
594 long len = config->str().length();
606 // FIX: Treat tabs as spaces
609 if ((c == '<') && (!in_quotes))
620 // FIX: Tab can follow a tagname as well as space.
621 } while ((c != ' ') && (c != 9));
625 in_quotes = (!in_quotes);
627 if ((c == '>') && (!in_quotes))
632 if (!strcmp(c_tag,tag))
634 if ((buffer) && (c_tag) && (var))
636 key = strstr(buffer,var);
639 /* value not found in tag */
657 for (unsigned j = 0; j < strlen(key); j++)
664 strlcpy(result,key,MAXBUF);
670 if (!strcmp(c_tag,tag))
672 /* correct tag, but wrong index */
682 if ((in_token) && (c != '\n') && (c != '\r'))
689 strcpy(result,""); // value or its tag not found at all
695 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
697 ReadConf(config, tag, var, index, result);
703 // This will bind a socket to a port. It works for UDP/TCP
704 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
706 memset((char *)&server,0,sizeof(server));
708 inet_aton(addr,&addy);
709 server.sin_family = AF_INET;
710 if (!strcmp(addr,""))
712 server.sin_addr.s_addr = htonl(INADDR_ANY);
716 server.sin_addr = addy;
718 server.sin_port = htons(port);
719 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
725 listen(sockfd, MaxConn);
732 int OpenTCPSocket (void)
736 struct linger linger = { 0 };
738 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
742 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
743 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
746 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));