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