]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Added PID reporting and testing before daemonize
[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[1mInspire Internet Relay Chat Server, compiled " __DATE__ " at " __TIME__ "\n");
67         printf("(C) ChatSpike Development team.\033[0;37m\n\n");
68         printf("Developers:\033[1m     Brain, FrostyCoolSlug\n");
69         printf("Documentation:\033[1m  FrostyCoolSlug, w00t\n");
70         printf("Testers:\033[1m        typobox43, piggles, Lord_Zathras, CC\n");
71         printf("Name concept:\033[1m   Lord_Zathras\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 (SIGABRT, Exit);
103         signal (SIGSEGV, Error);
104         signal (SIGURG, Exit);
105         signal (SIGKILL, Exit);
106         if ((childpid = fork ()) < 0)
107                 return (ERROR);
108         else if (childpid > 0)
109                 exit (0);
110         setsid ();
111         umask (007);
112         printf("InspIRCd PID: %d\n",getpid());
113         /* close stdin, stdout, stderr */
114         freopen("/dev/null","w",stdout);
115         freopen("/dev/null","w",stderr);
116         
117         setpriority(PRIO_PROCESS,(int)getpid(),15); /* ircd sets to low process priority so it doesnt hog the box */
118
119         if (unlimitcore)
120         {
121                 rlimit rl;
122                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
123                 {
124                         log(DEFAULT,"Failed to getrlimit()!");
125                         return(FALSE);
126                 }
127                 else
128                 {
129                         rl.rlim_cur = rl.rlim_max;
130                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
131                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
132                 }
133         }
134   
135         return (TRUE);
136 }
137
138
139 /* Make Sure Modules Are Avaliable!
140  * (BugFix By Craig.. See? I do work! :p)
141  * Modified by brain, requires const char*
142  * to work with other API functions
143  */
144
145 bool FileExists (const char* file)
146 {
147         FILE *input;
148         if ((input = fopen (file, "r")) == NULL)
149         {
150                 return(false);
151         }
152         else
153         {
154                 fclose (input);
155                 return(true);
156         }
157 }
158
159 /* ConfProcess does the following things to a config line in the following order:
160  *
161  * Processes the line for syntax errors as shown below
162  *      (1) Line void of quotes or equals (a malformed, illegal tag format)
163  *      (2) Odd number of quotes on the line indicating a missing quote
164  *      (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
165  *      (4) Spaces between the opening bracket (<) and the keyword
166  *      (5) Spaces between a keyword and an equals sign
167  *      (6) Spaces between an equals sign and a quote
168  * Removes trailing spaces
169  * Removes leading spaces
170  * Converts tabs to spaces
171  * Turns multiple spaces that are outside of quotes into single spaces
172  */
173
174 std::string ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
175 {
176         long number_of_quotes = 0;
177         long number_of_equals = 0;
178         bool has_open_bracket = false;
179         bool in_quotes = false;
180         error = false;
181         if (!buffer)
182         {
183                 return "";
184         }
185         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
186         for (int d = 0; d < strlen(buffer); d++)
187                 if ((buffer[d]) == 9)
188                         buffer[d] = ' ';
189         while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
190         while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
191         // empty lines are syntactically valid
192         if (!strcmp(buffer,""))
193                 return "";
194         else if (buffer[0] == '#')
195                 return "";
196         for (int c = 0; c < strlen(buffer); c++)
197         {
198                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
199                 // search and replace later :)
200                 if ((!in_quotes) && (buffer[c] == ' '))
201                         buffer[c] = '\xA0';
202                 if ((buffer[c] == '<') && (!in_quotes))
203                 {
204                         has_open_bracket = true;
205                         if (strlen(buffer) == 1)
206                         {
207                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
208                                 error = true;
209                                 return "";
210                         }
211                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
212                         {
213                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
214                                 error = true;
215                                 return "";
216                         }
217                 }
218                 if (buffer[c] == '"')
219                 {
220                         number_of_quotes++;
221                         in_quotes = (!in_quotes);
222                 }
223                 if ((buffer[c] == '=') && (!in_quotes))
224                 {
225                         number_of_equals++;
226                         if (strlen(buffer) == c)
227                         {
228                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
229                                 error = true;
230                                 return "";
231                         }
232                         else if (buffer[c+1] != '"')
233                         {
234                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
235                                 error = true;
236                                 return "";
237                         }
238                         else if (!c)
239                         {
240                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
241                                 error = true;
242                                 return "";
243                         }
244                         else if (buffer[c-1] == '\xA0')
245                         {
246                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
247                                 error = true;
248                                 return "";
249                         }
250                 }
251         }
252         // no quotes, and no equals. something freaky.
253         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
254         {
255                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
256                 error = true;
257                 return "";
258         }
259         // odd number of quotes. thats just wrong.
260         if ((number_of_quotes % 2) != 0)
261         {
262                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
263                 error = true;
264                 return "";
265         }
266         if (number_of_equals < (number_of_quotes/2))
267         {
268                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
269         }
270         if (number_of_equals > (number_of_quotes/2))
271         {
272                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
273         }
274
275         std::string parsedata = buffer;
276         // turn multispace into single space
277         while (parsedata.find("\xA0\xA0") != std::string::npos)
278         {
279                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
280         }
281
282         // turn our hardspace back into softspace
283         for (int d = 0; d < parsedata.length(); d++)
284         {
285                 if (parsedata[d] == '\xA0')
286                         parsedata[d] = ' ';
287         }
288
289         // and we're done, the line is fine!
290         return parsedata;
291 }
292
293 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
294 {
295         target->str("");
296         errorstream->str("");
297         long linenumber = 1;
298         // first, check that the file exists before we try to do anything with it
299         if (!FileExists(filename))
300         {
301                 *errorstream << "File " << filename << " not found." << endl;
302                 return false;
303         }
304         // Fix the chmod of the file to restrict it to the current user and group
305         chmod(filename,0600);
306         // now open it
307         FILE* conf = fopen(filename,"r");
308         char buffer[MAXBUF];
309         if (conf)
310         {
311                 while (!feof(conf))
312                 {
313                         if (fgets(buffer, MAXBUF, conf))
314                         {
315                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
316                                 {
317                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
318                                         {
319                                                 bool error = false;
320                                                 std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
321                                                 if (error)
322                                                 {
323                                                         return false;
324                                                 }
325                                                 *target << data;
326                                         }
327                                         else linenumber++;
328                                 }
329                         }
330                 }
331                 fclose(conf);
332         }
333         target->seekg(0);
334         return true;
335 }
336
337 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
338
339 int EnumConf(std::stringstream *config, const char* tag)
340 {
341         int ptr = 0;
342         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
343         int in_token, in_quotes, tptr, j, idx = 0;
344         char* key;
345
346         const char* buf = config->str().c_str();
347         long bptr = 0;
348         long len = strlen(buf);
349         
350         ptr = 0;
351         in_token = 0;
352         in_quotes = 0;
353         lastc = '\0';
354         while (bptr<len)
355         {
356                 lastc = c;
357                 c = buf[bptr++];
358                 if ((c == '#') && (lastc == '\n'))
359                 {
360                         while ((c != '\n') && (bptr<len))
361                         {
362                                 lastc = c;
363                                 c = buf[bptr++];
364                         }
365                 }
366                 if ((c == '<') && (!in_quotes))
367                 {
368                         tptr = 0;
369                         in_token = 1;
370                         do {
371                                 c = buf[bptr++];
372                                 if (c != ' ')
373                                 {
374                                         c_tag[tptr++] = c;
375                                         c_tag[tptr] = '\0';
376                                 }
377                         } while (c != ' ');
378                 }
379                 if (c == '"')
380                 {
381                         in_quotes = (!in_quotes);
382                 }
383                 if ((c == '>') && (!in_quotes))
384                 {
385                         in_token = 0;
386                         if (!strcmp(c_tag,tag))
387                         {
388                                 /* correct tag, but wrong index */
389                                 idx++;
390                         }
391                         c_tag[0] = '\0';
392                         buffer[0] = '\0';
393                         ptr = 0;
394                         tptr = 0;
395                 }
396                 if (c != '>')
397                 {
398                         if ((in_token) && (c != '\n') && (c != '\r'))
399                         {
400                                 buffer[ptr++] = c;
401                                 buffer[ptr] = '\0';
402                         }
403                 }
404         }
405         return idx;
406 }
407
408 /* Counts the number of values within a certain tag */
409
410 int EnumValues(std::stringstream *config, const char* tag, int index)
411 {
412         int ptr = 0;
413         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
414         int in_token, in_quotes, tptr, j, idx = 0;
415         char* key;
416         
417         bool correct_tag = false;
418         int num_items = 0;
419
420         const char* buf = config->str().c_str();
421         long bptr = 0;
422         long len = strlen(buf);
423         
424         ptr = 0;
425         in_token = 0;
426         in_quotes = 0;
427         lastc = '\0';
428         while (bptr<len)
429         {
430                 lastc = c;
431                 c = buf[bptr++];
432                 if ((c == '#') && (lastc == '\n'))
433                 {
434                         while ((c != '\n') && (bptr<len))
435                         {
436                                 lastc = c;
437                                 c = buf[bptr++];
438                         }
439                 }
440                 if ((c == '<') && (!in_quotes))
441                 {
442                         tptr = 0;
443                         in_token = 1;
444                         do {
445                                 c = buf[bptr++];
446                                 if (c != ' ')
447                                 {
448                                         c_tag[tptr++] = c;
449                                         c_tag[tptr] = '\0';
450                                         
451                                         if ((!strcmp(c_tag,tag)) && (idx == index))
452                                         {
453                                                 correct_tag = true;
454                                         }
455                                 }
456                         } while (c != ' ');
457                 }
458                 if (c == '"')
459                 {
460                         in_quotes = (!in_quotes);
461                 }
462                 
463                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
464                 {
465                         num_items++;
466                 }
467                 if ((c == '>') && (!in_quotes))
468                 {
469                         in_token = 0;
470                         if (correct_tag)
471                                 correct_tag = false;
472                         if (!strcmp(c_tag,tag))
473                         {
474                                 /* correct tag, but wrong index */
475                                 idx++;
476                         }
477                         c_tag[0] = '\0';
478                         buffer[0] = '\0';
479                         ptr = 0;
480                         tptr = 0;
481                 }
482                 if (c != '>')
483                 {
484                         if ((in_token) && (c != '\n') && (c != '\r'))
485                         {
486                                 buffer[ptr++] = c;
487                                 buffer[ptr] = '\0';
488                         }
489                 }
490         }
491         return num_items+1;
492 }
493
494
495
496 int ConfValueEnum(char* tag, std::stringstream* config)
497 {
498         return EnumConf(config,tag);
499 }
500
501
502
503 /* Retrieves a value from the config file. If there is more than one value of the specified
504  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
505  *
506  * ConfValue("oper","name",2,result);
507  */
508
509 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
510 {
511         int ptr = 0;
512         char buffer[65535], c_tag[MAXBUF], c, lastc;
513         int in_token, in_quotes, tptr, j, idx = 0;
514         char* key;
515
516         const char* buf = config->str().c_str();
517         long bptr = 0;
518         long len = strlen(buf);
519         
520         ptr = 0;
521         in_token = 0;
522         in_quotes = 0;
523         lastc = '\0';
524         c_tag[0] = '\0';
525         buffer[0] = '\0';
526         while (bptr<len)
527         {
528                 lastc = c;
529                 c = buf[bptr++];
530                 // FIX: Treat tabs as spaces
531                 if (c == 9)
532                         c = 32;
533                 if ((c == '<') && (!in_quotes))
534                 {
535                         tptr = 0;
536                         in_token = 1;
537                         do {
538                                 c = buf[bptr++];
539                                 if (c != ' ')
540                                 {
541                                         c_tag[tptr++] = c;
542                                         c_tag[tptr] = '\0';
543                                 }
544                         // FIX: Tab can follow a tagname as well as space.
545                         } while ((c != ' ') && (c != 9));
546                 }
547                 if (c == '"')
548                 {
549                         in_quotes = (!in_quotes);
550                 }
551                 if ((c == '>') && (!in_quotes))
552                 {
553                         in_token = 0;
554                         if (idx == index)
555                         {
556                                 if (!strcmp(c_tag,tag))
557                                 {
558                                         if ((buffer) && (c_tag) && (var))
559                                         {
560                                                 key = strstr(buffer,var);
561                                                 if (!key)
562                                                 {
563                                                         /* value not found in tag */
564                                                         strcpy(result,"");
565                                                         return 0;
566                                                 }
567                                                 else
568                                                 {
569                                                         key+=strlen(var);
570                                                         while (key[0] !='"')
571                                                         {
572                                                                 if (!strlen(key))
573                                                                 {
574                                                                         /* missing quote */
575                                                                         strcpy(result,"");
576                                                                         return 0;
577                                                                 }
578                                                                 key++;
579                                                         }
580                                                         key++;
581                                                         for (j = 0; j < strlen(key); j++)
582                                                         {
583                                                                 if (key[j] == '"')
584                                                                 {
585                                                                         key[j] = '\0';
586                                                                 }
587                                                         }
588                                                         strlcpy(result,key,MAXBUF);
589                                                         return 1;
590                                                 }
591                                         }
592                                 }
593                         }
594                         if (!strcmp(c_tag,tag))
595                         {
596                                 /* correct tag, but wrong index */
597                                 idx++;
598                         }
599                         c_tag[0] = '\0';
600                         buffer[0] = '\0';
601                         ptr = 0;
602                         tptr = 0;
603                 }
604                 if (c != '>')
605                 {
606                         if ((in_token) && (c != '\n') && (c != '\r'))
607                         {
608                                 buffer[ptr++] = c;
609                                 buffer[ptr] = '\0';
610                         }
611                 }
612         }
613         strcpy(result,""); // value or its tag not found at all
614         return 0;
615 }
616
617
618
619 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
620 {
621         ReadConf(config, tag, var, index, result);
622         return 0;
623 }
624
625
626
627 // This will bind a socket to a port. It works for UDP/TCP
628 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
629 {
630         bzero((char *)&server,sizeof(server));
631         struct in_addr addy;
632         inet_aton(addr,&addy);
633         server.sin_family = AF_INET;
634         if (!strcmp(addr,""))
635         {
636                 server.sin_addr.s_addr = htonl(INADDR_ANY);
637         }
638         else
639         {
640                 server.sin_addr = addy;
641         }
642         server.sin_port = htons(port);
643         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
644         {
645                 return(ERROR);
646         }
647         else
648         {
649                 listen(sockfd,5);
650                 return(TRUE);
651         }
652 }
653
654
655 // Open a TCP Socket
656 int OpenTCPSocket (void)
657 {
658         int sockfd;
659         int on = 1;
660         struct linger linger = { 0 };
661   
662         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
663                 return (ERROR);
664         else
665         {
666                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
667                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
668                 linger.l_onoff = 1;
669                 linger.l_linger = 1;
670                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
671                 return (sockfd);
672         }
673 }
674