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