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