]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Cannot initialize kqueue BEFORE the daemon fork!
[user/henk/code/inspircd.git] / src / inspircd_io.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include <sys/time.h>
18 #include <sys/resource.h>
19 #include <sys/types.h>
20 #include <string>
21 #include <unistd.h>
22 #include <sstream>
23 #include <iostream>
24 #include <fstream>
25 #include "inspircd.h"
26 #include "inspircd_io.h"
27 #include "inspircd_util.h"
28 #include "inspstring.h"
29
30 using namespace std;
31
32 extern FILE *log_file;
33 extern int boundPortCount;
34 extern int openSockfd[MAXSOCKS];
35 extern time_t TIME;
36 extern bool unlimitcore;
37
38 void WriteOpers(char* text, ...);
39
40 void Exit (int status)
41 {
42         if (log_file)
43                 fclose(log_file);
44         send_error("Server shutdown.");
45         exit (status);
46 }
47
48 void Killed(int status)
49 {
50         if (log_file)
51                 fclose(log_file);
52         send_error("Server terminated.");
53         exit(status);
54 }
55
56 void Rehash(int status)
57 {
58         WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
59         ReadConfig(false,NULL);
60 }
61
62
63
64 void Start (void)
65 {
66         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
67         printf("(C) ChatSpike Development team.\033[0m\n\n");
68         printf("Developers:\033[1;32m     Brain, FrostyCoolSlug\033[0m\n");
69         printf("Documentation:\033[1;32m  FrostyCoolSlug, w00t\033[0m\n");
70         printf("Testers:\033[1;32m        typobox43, piggles, Lord_Zathras, CC\033[0m\n");
71         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
72 }
73
74 void WritePID(std::string filename)
75 {
76         ofstream outfile(filename.c_str());
77         if (outfile.is_open())
78         {
79                 outfile << getpid();
80                 outfile.close();
81         }
82         else
83         {
84                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
85                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
86                 Exit(0);
87         }
88 }
89
90 void DeadPipe(int status)
91 {
92   signal (SIGPIPE, DeadPipe);
93 }
94
95 int DaemonSeed (void)
96 {
97         int childpid;
98         signal (SIGALRM, SIG_IGN);
99         signal (SIGHUP, Rehash);
100         signal (SIGPIPE, DeadPipe);
101         signal (SIGTERM, Exit);
102         signal (SIGSEGV, Error);
103         if ((childpid = fork ()) < 0)
104                 return (ERROR);
105         else if (childpid > 0)
106                 exit (0);
107         setsid ();
108         umask (007);
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);
112         
113         setpriority(PRIO_PROCESS,(int)getpid(),15);
114
115         if (unlimitcore)
116         {
117                 rlimit rl;
118                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
119                 {
120                         log(DEFAULT,"Failed to getrlimit()!");
121                         return(FALSE);
122                 }
123                 else
124                 {
125                         rl.rlim_cur = rl.rlim_max;
126                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
127                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
128                 }
129         }
130   
131         return (TRUE);
132 }
133
134
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
139  */
140
141 bool FileExists (const char* file)
142 {
143         FILE *input;
144         if ((input = fopen (file, "r")) == NULL)
145         {
146                 return(false);
147         }
148         else
149         {
150                 fclose (input);
151                 return(true);
152         }
153 }
154
155 /* ConfProcess does the following things to a config line in the following order:
156  *
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
168  */
169
170 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
171 {
172         long number_of_quotes = 0;
173         long number_of_equals = 0;
174         bool has_open_bracket = false;
175         bool in_quotes = false;
176         error = false;
177         if (!buffer)
178         {
179                 return "";
180         }
181         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
182         for (int d = 0; d < strlen(buffer); d++)
183                 if ((buffer[d]) == 9)
184                         buffer[d] = ' ';
185         while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
186         while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
187         // empty lines are syntactically valid
188         if (!strcmp(buffer,""))
189                 return "";
190         else if (buffer[0] == '#')
191                 return "";
192         for (int c = 0; c < strlen(buffer); c++)
193         {
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] == ' '))
197                         buffer[c] = '\xA0';
198                 if ((buffer[c] == '<') && (!in_quotes))
199                 {
200                         has_open_bracket = true;
201                         if (strlen(buffer) == 1)
202                         {
203                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
204                                 error = true;
205                                 return "";
206                         }
207                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
208                         {
209                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
210                                 error = true;
211                                 return "";
212                         }
213                 }
214                 if (buffer[c] == '"')
215                 {
216                         number_of_quotes++;
217                         in_quotes = (!in_quotes);
218                 }
219                 if ((buffer[c] == '=') && (!in_quotes))
220                 {
221                         number_of_equals++;
222                         if (strlen(buffer) == c)
223                         {
224                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
225                                 error = true;
226                                 return "";
227                         }
228                         else if (buffer[c+1] != '"')
229                         {
230                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
231                                 error = true;
232                                 return "";
233                         }
234                         else if (!c)
235                         {
236                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
237                                 error = true;
238                                 return "";
239                         }
240                         else if (buffer[c-1] == '\xA0')
241                         {
242                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
243                                 error = true;
244                                 return "";
245                         }
246                 }
247         }
248         // no quotes, and no equals. something freaky.
249         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
250         {
251                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
252                 error = true;
253                 return "";
254         }
255         // odd number of quotes. thats just wrong.
256         if ((number_of_quotes % 2) != 0)
257         {
258                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
259                 error = true;
260                 return "";
261         }
262         if (number_of_equals < (number_of_quotes/2))
263         {
264                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
265         }
266         if (number_of_equals > (number_of_quotes/2))
267         {
268                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
269         }
270
271         std::string parsedata = buffer;
272         // turn multispace into single space
273         while (parsedata.find("\xA0\xA0") != std::string::npos)
274         {
275                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
276         }
277
278         // turn our hardspace back into softspace
279         for (int d = 0; d < parsedata.length(); d++)
280         {
281                 if (parsedata[d] == '\xA0')
282                         parsedata[d] = ' ';
283         }
284
285         // and we're done, the line is fine!
286         return parsedata;
287 }
288
289 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
290 {
291         target->str("");
292         errorstream->str("");
293         long linenumber = 1;
294         // first, check that the file exists before we try to do anything with it
295         if (!FileExists(filename))
296         {
297                 *errorstream << "File " << filename << " not found." << endl;
298                 return false;
299         }
300         // Fix the chmod of the file to restrict it to the current user and group
301         chmod(filename,0600);
302         // now open it
303         FILE* conf = fopen(filename,"r");
304         char buffer[MAXBUF];
305         if (conf)
306         {
307                 while (!feof(conf))
308                 {
309                         if (fgets(buffer, MAXBUF, conf))
310                         {
311                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
312                                 {
313                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
314                                         {
315                                                 bool error = false;
316                                                 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
317                                                 if (error)
318                                                 {
319                                                         return false;
320                                                 }
321                                                 *target << data;
322                                         }
323                                         else linenumber++;
324                                 }
325                         }
326                 }
327                 fclose(conf);
328         }
329         target->seekg(0);
330         return true;
331 }
332
333 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
334
335 int EnumConf(std::stringstream *config, const char* tag)
336 {
337         int ptr = 0;
338         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
339         int in_token, in_quotes, tptr, idx = 0;
340
341         const char* buf = config->str().c_str();
342         long bptr = 0;
343         long len = strlen(buf);
344         
345         ptr = 0;
346         in_token = 0;
347         in_quotes = 0;
348         lastc = '\0';
349         while (bptr<len)
350         {
351                 lastc = c;
352                 c = buf[bptr++];
353                 if ((c == '#') && (lastc == '\n'))
354                 {
355                         while ((c != '\n') && (bptr<len))
356                         {
357                                 lastc = c;
358                                 c = buf[bptr++];
359                         }
360                 }
361                 if ((c == '<') && (!in_quotes))
362                 {
363                         tptr = 0;
364                         in_token = 1;
365                         do {
366                                 c = buf[bptr++];
367                                 if (c != ' ')
368                                 {
369                                         c_tag[tptr++] = c;
370                                         c_tag[tptr] = '\0';
371                                 }
372                         } while (c != ' ');
373                 }
374                 if (c == '"')
375                 {
376                         in_quotes = (!in_quotes);
377                 }
378                 if ((c == '>') && (!in_quotes))
379                 {
380                         in_token = 0;
381                         if (!strcmp(c_tag,tag))
382                         {
383                                 /* correct tag, but wrong index */
384                                 idx++;
385                         }
386                         c_tag[0] = '\0';
387                         buffer[0] = '\0';
388                         ptr = 0;
389                         tptr = 0;
390                 }
391                 if (c != '>')
392                 {
393                         if ((in_token) && (c != '\n') && (c != '\r'))
394                         {
395                                 buffer[ptr++] = c;
396                                 buffer[ptr] = '\0';
397                         }
398                 }
399         }
400         return idx;
401 }
402
403 /* Counts the number of values within a certain tag */
404
405 int EnumValues(std::stringstream *config, const char* tag, int index)
406 {
407         int ptr = 0;
408         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
409         int in_token, in_quotes, tptr, idx = 0;
410         
411         bool correct_tag = false;
412         int num_items = 0;
413
414         const char* buf = config->str().c_str();
415         long bptr = 0;
416         long len = strlen(buf);
417         
418         ptr = 0;
419         in_token = 0;
420         in_quotes = 0;
421         lastc = '\0';
422         while (bptr<len)
423         {
424                 lastc = c;
425                 c = buf[bptr++];
426                 if ((c == '#') && (lastc == '\n'))
427                 {
428                         while ((c != '\n') && (bptr<len))
429                         {
430                                 lastc = c;
431                                 c = buf[bptr++];
432                         }
433                 }
434                 if ((c == '<') && (!in_quotes))
435                 {
436                         tptr = 0;
437                         in_token = 1;
438                         do {
439                                 c = buf[bptr++];
440                                 if (c != ' ')
441                                 {
442                                         c_tag[tptr++] = c;
443                                         c_tag[tptr] = '\0';
444                                         
445                                         if ((!strcmp(c_tag,tag)) && (idx == index))
446                                         {
447                                                 correct_tag = true;
448                                         }
449                                 }
450                         } while (c != ' ');
451                 }
452                 if (c == '"')
453                 {
454                         in_quotes = (!in_quotes);
455                 }
456                 
457                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
458                 {
459                         num_items++;
460                 }
461                 if ((c == '>') && (!in_quotes))
462                 {
463                         in_token = 0;
464                         if (correct_tag)
465                                 correct_tag = false;
466                         if (!strcmp(c_tag,tag))
467                         {
468                                 /* correct tag, but wrong index */
469                                 idx++;
470                         }
471                         c_tag[0] = '\0';
472                         buffer[0] = '\0';
473                         ptr = 0;
474                         tptr = 0;
475                 }
476                 if (c != '>')
477                 {
478                         if ((in_token) && (c != '\n') && (c != '\r'))
479                         {
480                                 buffer[ptr++] = c;
481                                 buffer[ptr] = '\0';
482                         }
483                 }
484         }
485         return num_items+1;
486 }
487
488
489
490 int ConfValueEnum(char* tag, std::stringstream* config)
491 {
492         return EnumConf(config,tag);
493 }
494
495
496
497 /* Retrieves a value from the config file. If there is more than one value of the specified
498  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
499  *
500  * ConfValue("oper","name",2,result);
501  */
502
503 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
504 {
505         int ptr = 0;
506         char buffer[65535], c_tag[MAXBUF], c, lastc;
507         int in_token, in_quotes, tptr, j, idx = 0;
508         char* key;
509
510         const char* buf = config->str().c_str();
511         long bptr = 0;
512         long len = config->str().length();
513         
514         ptr = 0;
515         in_token = 0;
516         in_quotes = 0;
517         lastc = '\0';
518         c_tag[0] = '\0';
519         buffer[0] = '\0';
520         while (bptr<len)
521         {
522                 lastc = c;
523                 c = buf[bptr++];
524                 // FIX: Treat tabs as spaces
525                 if (c == 9)
526                         c = 32;
527                 if ((c == '<') && (!in_quotes))
528                 {
529                         tptr = 0;
530                         in_token = 1;
531                         do {
532                                 c = buf[bptr++];
533                                 if (c != ' ')
534                                 {
535                                         c_tag[tptr++] = c;
536                                         c_tag[tptr] = '\0';
537                                 }
538                         // FIX: Tab can follow a tagname as well as space.
539                         } while ((c != ' ') && (c != 9));
540                 }
541                 if (c == '"')
542                 {
543                         in_quotes = (!in_quotes);
544                 }
545                 if ((c == '>') && (!in_quotes))
546                 {
547                         in_token = 0;
548                         if (idx == index)
549                         {
550                                 if (!strcmp(c_tag,tag))
551                                 {
552                                         if ((buffer) && (c_tag) && (var))
553                                         {
554                                                 key = strstr(buffer,var);
555                                                 if (!key)
556                                                 {
557                                                         /* value not found in tag */
558                                                         strcpy(result,"");
559                                                         return 0;
560                                                 }
561                                                 else
562                                                 {
563                                                         key+=strlen(var);
564                                                         while (key[0] !='"')
565                                                         {
566                                                                 if (!strlen(key))
567                                                                 {
568                                                                         /* missing quote */
569                                                                         strcpy(result,"");
570                                                                         return 0;
571                                                                 }
572                                                                 key++;
573                                                         }
574                                                         key++;
575                                                         for (j = 0; j < strlen(key); j++)
576                                                         {
577                                                                 if (key[j] == '"')
578                                                                 {
579                                                                         key[j] = '\0';
580                                                                 }
581                                                         }
582                                                         strlcpy(result,key,MAXBUF);
583                                                         return 1;
584                                                 }
585                                         }
586                                 }
587                         }
588                         if (!strcmp(c_tag,tag))
589                         {
590                                 /* correct tag, but wrong index */
591                                 idx++;
592                         }
593                         c_tag[0] = '\0';
594                         buffer[0] = '\0';
595                         ptr = 0;
596                         tptr = 0;
597                 }
598                 if (c != '>')
599                 {
600                         if ((in_token) && (c != '\n') && (c != '\r'))
601                         {
602                                 buffer[ptr++] = c;
603                                 buffer[ptr] = '\0';
604                         }
605                 }
606         }
607         strcpy(result,""); // value or its tag not found at all
608         return 0;
609 }
610
611
612
613 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
614 {
615         ReadConf(config, tag, var, index, result);
616         return 0;
617 }
618
619
620
621 // This will bind a socket to a port. It works for UDP/TCP
622 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
623 {
624         bzero((char *)&server,sizeof(server));
625         struct in_addr addy;
626         inet_aton(addr,&addy);
627         server.sin_family = AF_INET;
628         if (!strcmp(addr,""))
629         {
630                 server.sin_addr.s_addr = htonl(INADDR_ANY);
631         }
632         else
633         {
634                 server.sin_addr = addy;
635         }
636         server.sin_port = htons(port);
637         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
638         {
639                 return(ERROR);
640         }
641         else
642         {
643                 listen(sockfd,5);
644                 return(TRUE);
645         }
646 }
647
648
649 // Open a TCP Socket
650 int OpenTCPSocket (void)
651 {
652         int sockfd;
653         int on = 1;
654         struct linger linger = { 0 };
655   
656         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
657                 return (ERROR);
658         else
659         {
660                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
661                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
662                 linger.l_onoff = 1;
663                 linger.l_linger = 1;
664                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
665                 return (sockfd);
666         }
667 }
668