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());
111 setpriority(PRIO_PROCESS,(int)getpid(),15);
116 if (getrlimit(RLIMIT_CORE, &rl) == -1)
118 log(DEFAULT,"Failed to getrlimit()!");
123 rl.rlim_cur = rl.rlim_max;
124 if (setrlimit(RLIMIT_CORE, &rl) == -1)
125 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
133 /* Make Sure Modules Are Avaliable!
134 * (BugFix By Craig.. See? I do work! :p)
135 * Modified by brain, requires const char*
136 * to work with other API functions
139 bool FileExists (const char* file)
142 if ((input = fopen (file, "r")) == NULL)
153 /* ConfProcess does the following things to a config line in the following order:
155 * Processes the line for syntax errors as shown below
156 * (1) Line void of quotes or equals (a malformed, illegal tag format)
157 * (2) Odd number of quotes on the line indicating a missing quote
158 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
159 * (4) Spaces between the opening bracket (<) and the keyword
160 * (5) Spaces between a keyword and an equals sign
161 * (6) Spaces between an equals sign and a quote
162 * Removes trailing spaces
163 * Removes leading spaces
164 * Converts tabs to spaces
165 * Turns multiple spaces that are outside of quotes into single spaces
168 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
170 long number_of_quotes = 0;
171 long number_of_equals = 0;
172 bool has_open_bracket = false;
173 bool in_quotes = false;
179 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
180 for (unsigned int d = 0; d < strlen(buffer); d++)
181 if ((buffer[d]) == 9)
183 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
184 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
186 // empty lines are syntactically valid, as are comments
187 if (!(*buffer) || buffer[0] == '#')
190 for (unsigned int c = 0; c < strlen(buffer); c++)
192 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
193 // search and replace later :)
194 if ((!in_quotes) && (buffer[c] == ' '))
196 if ((buffer[c] == '<') && (!in_quotes))
198 has_open_bracket = true;
199 if (strlen(buffer) == 1)
201 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
205 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
207 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
212 if (buffer[c] == '"')
215 in_quotes = (!in_quotes);
217 if ((buffer[c] == '=') && (!in_quotes))
220 if (strlen(buffer) == c)
222 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
226 else if (buffer[c+1] != '"')
228 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
234 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
238 else if (buffer[c-1] == '\xA0')
240 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
246 // no quotes, and no equals. something freaky.
247 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
249 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
253 // odd number of quotes. thats just wrong.
254 if ((number_of_quotes % 2) != 0)
256 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
260 if (number_of_equals < (number_of_quotes/2))
262 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
264 if (number_of_equals > (number_of_quotes/2))
266 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
269 std::string parsedata = buffer;
270 // turn multispace into single space
271 while (parsedata.find("\xA0\xA0") != std::string::npos)
273 parsedata.erase(parsedata.find("\xA0\xA0"),1);
276 // turn our hardspace back into softspace
277 for (unsigned int d = 0; d < parsedata.length(); d++)
279 if (parsedata[d] == '\xA0')
283 // and we're done, the line is fine!
287 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
290 unsigned int bufptr = 0;
291 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
293 c_read = fgetc(file);
294 if ((c_read != '\n') && (c_read != '\r'))
295 buffer[bufptr++] = c_read;
297 buffer[bufptr] = '\0';
301 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
304 errorstream->str("");
306 // first, check that the file exists before we try to do anything with it
307 if (!FileExists(filename))
309 *errorstream << "File " << filename << " not found." << endl;
312 // Fix the chmod of the file to restrict it to the current user and group
313 chmod(filename,0600);
314 for (unsigned int t = 0; t < include_stack.size(); t++)
316 if (std::string(filename) == include_stack[t])
318 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
322 include_stack.push_back(filename);
324 FILE* conf = fopen(filename,"r");
330 if (fgets_safe(buffer, MAXBUF, conf))
332 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
334 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
336 if (!strncmp(buffer,"<include file=\"",15))
339 char confpath[10240],newconf[10240];
340 // include file directive
341 buf += 15; // advance to filename
342 for (unsigned int j = 0; j < strlen(buf); j++)
352 log(DEFAULT,"Opening included file '%s'",buf);
355 strlcpy(confpath,CONFIG_FILE,10240);
356 if (strstr(confpath,"/inspircd.conf"))
358 // leaves us with just the path
359 *(strstr(confpath,"/inspircd.conf")) = '\0';
361 snprintf(newconf,10240,"%s/%s",confpath,buf);
363 else snprintf(newconf,10240,"%s",buf);
364 std::stringstream merge(stringstream::in | stringstream::out);
365 // recursively call LoadConf and get the new data, use the same errorstream
366 if (LoadConf(newconf, &merge, errorstream))
368 // append to the end of the file
369 std::string newstuff = merge.str();
374 // the error propogates up to its parent recursively
375 // causing the config reader to bail at the top level.
383 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
401 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
403 int EnumConf(std::stringstream *config, const char* tag)
406 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
407 int in_token, in_quotes, tptr, idx = 0;
409 const char* buf = config->str().c_str();
411 long len = strlen(buf);
421 if ((c == '#') && (lastc == '\n'))
423 while ((c != '\n') && (bptr<len))
429 if ((c == '<') && (!in_quotes))
444 in_quotes = (!in_quotes);
446 if ((c == '>') && (!in_quotes))
449 if (!strcmp(c_tag,tag))
451 /* correct tag, but wrong index */
461 if ((in_token) && (c != '\n') && (c != '\r'))
471 /* Counts the number of values within a certain tag */
473 int EnumValues(std::stringstream *config, const char* tag, int index)
476 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
477 int in_token, in_quotes, tptr, idx = 0;
479 bool correct_tag = false;
482 const char* buf = config->str().c_str();
484 long len = strlen(buf);
494 if ((c == '#') && (lastc == '\n'))
496 while ((c != '\n') && (bptr<len))
502 if ((c == '<') && (!in_quotes))
513 if ((!strcmp(c_tag,tag)) && (idx == index))
522 in_quotes = (!in_quotes);
525 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
529 if ((c == '>') && (!in_quotes))
534 if (!strcmp(c_tag,tag))
536 /* correct tag, but wrong index */
546 if ((in_token) && (c != '\n') && (c != '\r'))
558 int ConfValueEnum(char* tag, std::stringstream* config)
560 return EnumConf(config,tag);
565 /* Retrieves a value from the config file. If there is more than one value of the specified
566 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
568 * ConfValue("oper","name",2,result);
571 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
574 char buffer[65535], c_tag[MAXBUF], c, lastc;
575 int in_token, in_quotes, tptr, idx = 0;
578 const char* buf = config->str().c_str();
580 long len = config->str().length();
592 // FIX: Treat tabs as spaces
595 if ((c == '<') && (!in_quotes))
606 // FIX: Tab can follow a tagname as well as space.
607 } while ((c != ' ') && (c != 9));
611 in_quotes = (!in_quotes);
613 if ((c == '>') && (!in_quotes))
618 if (!strcmp(c_tag,tag))
620 if ((buffer) && (c_tag) && (var))
622 key = strstr(buffer,var);
625 /* value not found in tag */
643 for (unsigned j = 0; j < strlen(key); j++)
650 strlcpy(result,key,MAXBUF);
656 if (!strcmp(c_tag,tag))
658 /* correct tag, but wrong index */
668 if ((in_token) && (c != '\n') && (c != '\r'))
675 strcpy(result,""); // value or its tag not found at all
681 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
683 ReadConf(config, tag, var, index, result);
689 // This will bind a socket to a port. It works for UDP/TCP
690 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
692 memset((char *)&server,0,sizeof(server));
694 inet_aton(addr,&addy);
695 server.sin_family = AF_INET;
696 if (!strcmp(addr,""))
698 server.sin_addr.s_addr = htonl(INADDR_ANY);
702 server.sin_addr = addy;
704 server.sin_port = htons(port);
705 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
711 listen(sockfd, MaxConn);
718 int OpenTCPSocket (void)
722 struct linger linger = { 0 };
724 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
728 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
729 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
732 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));