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