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