]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Changed comments
[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 /* A special version of fgets that will read \r, \n, \r\n or even \n\r, it doesnt care :-) */
290
291 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
292 {
293         char c_read = '\0';
294         unsigned int bufptr = 0;
295         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
296         {
297                 c_read = fgetc(file);
298                 if ((c_read != '\n') && (c_read != '\r'))
299                         buffer[bufptr++] = c_read;
300         }
301         buffer[bufptr] = '\0';
302         return bufptr;
303 }
304
305 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
306 {
307         target->str("");
308         errorstream->str("");
309         long linenumber = 1;
310         // first, check that the file exists before we try to do anything with it
311         if (!FileExists(filename))
312         {
313                 *errorstream << "File " << filename << " not found." << endl;
314                 return false;
315         }
316         // Fix the chmod of the file to restrict it to the current user and group
317         chmod(filename,0600);
318         for (unsigned int t = 0; t < include_stack.size(); t++)
319         {
320                 if (std::string(filename) == include_stack[t])
321                 {
322                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
323                         return false;
324                 }
325         }
326         include_stack.push_back(filename);
327         // now open it
328         FILE* conf = fopen(filename,"r");
329         char buffer[MAXBUF];
330         if (conf)
331         {
332                 while (!feof(conf))
333                 {
334                         *buffer = 0;
335                         if (fgets_safe(buffer, MAXBUF, conf))
336                         {
337                                 if ((buffer) && (strlen(buffer)) && (*buffer > '\r'))
338                                 {
339                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
340                                         {
341                                                 if (!strncmp(buffer,"<include file=\"",15))
342                                                 {
343                                                         char* buf = buffer;
344                                                         char confpath[10240],newconf[10240];
345                                                         // include file directive
346                                                         buf += 15;      // advance to filename
347                                                         for (unsigned int j = 0; j < strlen(buf); j++)
348                                                         {
349                                                                 if (buf[j] == '\\')
350                                                                         buf[j] = '/';
351                                                                 if (buf[j] == '"')
352                                                                 {
353                                                                         buf[j] = '\0';
354                                                                         break;
355                                                                 }
356                                                         }
357                                                         log(DEFAULT,"Opening included file '%s'",buf);
358                                                         if (*buf != '/')
359                                                         {
360                                                                 strlcpy(confpath,CONFIG_FILE,10240);
361                                                                 if (strstr(confpath,"/inspircd.conf"))
362                                                                 {
363                                                                         // leaves us with just the path
364                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
365                                                                 }
366                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
367                                                         }
368                                                         else snprintf(newconf,10240,"%s",buf);
369                                                         std::stringstream merge(stringstream::in | stringstream::out);
370                                                         // recursively call LoadConf and get the new data, use the same errorstream
371                                                         if (LoadConf(newconf, &merge, errorstream))
372                                                         {
373                                                                 // append to the end of the file
374                                                                 std::string newstuff = merge.str();
375                                                                 *target << newstuff;
376                                                         }
377                                                         else
378                                                         {
379                                                                 // the error propogates up to its parent recursively
380                                                                 // causing the config reader to bail at the top level.
381                                                                 fclose(conf);
382                                                                 return false;
383                                                         }
384                                                 }
385                                                 else
386                                                 {
387                                                         bool error = false;
388                                                         std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
389                                                         if (error)
390                                                         {
391                                                                 return false;
392                                                         }
393                                                         *target << data;
394                                                 }
395                                         }
396                                         else linenumber++;
397                                 }
398                         }
399                 }
400                 fclose(conf);
401         }
402         target->seekg(0);
403         return true;
404 }
405
406 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
407
408 int EnumConf(std::stringstream *config, const char* tag)
409 {
410         int ptr = 0;
411         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
412         int in_token, in_quotes, tptr, idx = 0;
413
414         const char* buf = config->str().c_str();
415         long bptr = 0;
416         long len = strlen(buf);
417         
418         ptr = 0;
419         in_token = 0;
420         in_quotes = 0;
421         lastc = '\0';
422         while (bptr<len)
423         {
424                 lastc = c;
425                 c = buf[bptr++];
426                 if ((c == '#') && (lastc == '\n'))
427                 {
428                         while ((c != '\n') && (bptr<len))
429                         {
430                                 lastc = c;
431                                 c = buf[bptr++];
432                         }
433                 }
434                 if ((c == '<') && (!in_quotes))
435                 {
436                         tptr = 0;
437                         in_token = 1;
438                         do {
439                                 c = buf[bptr++];
440                                 if (c != ' ')
441                                 {
442                                         c_tag[tptr++] = c;
443                                         c_tag[tptr] = '\0';
444                                 }
445                         } while (c != ' ');
446                 }
447                 if (c == '"')
448                 {
449                         in_quotes = (!in_quotes);
450                 }
451                 if ((c == '>') && (!in_quotes))
452                 {
453                         in_token = 0;
454                         if (!strcmp(c_tag,tag))
455                         {
456                                 /* correct tag, but wrong index */
457                                 idx++;
458                         }
459                         c_tag[0] = '\0';
460                         buffer[0] = '\0';
461                         ptr = 0;
462                         tptr = 0;
463                 }
464                 if (c != '>')
465                 {
466                         if ((in_token) && (c != '\n') && (c != '\r'))
467                         {
468                                 buffer[ptr++] = c;
469                                 buffer[ptr] = '\0';
470                         }
471                 }
472         }
473         return idx;
474 }
475
476 /* Counts the number of values within a certain tag */
477
478 int EnumValues(std::stringstream *config, const char* tag, int index)
479 {
480         int ptr = 0;
481         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
482         int in_token, in_quotes, tptr, idx = 0;
483         
484         bool correct_tag = false;
485         int num_items = 0;
486
487         const char* buf = config->str().c_str();
488         long bptr = 0;
489         long len = strlen(buf);
490         
491         ptr = 0;
492         in_token = 0;
493         in_quotes = 0;
494         lastc = '\0';
495         while (bptr<len)
496         {
497                 lastc = c;
498                 c = buf[bptr++];
499                 if ((c == '#') && (lastc == '\n'))
500                 {
501                         while ((c != '\n') && (bptr<len))
502                         {
503                                 lastc = c;
504                                 c = buf[bptr++];
505                         }
506                 }
507                 if ((c == '<') && (!in_quotes))
508                 {
509                         tptr = 0;
510                         in_token = 1;
511                         do {
512                                 c = buf[bptr++];
513                                 if (c != ' ')
514                                 {
515                                         c_tag[tptr++] = c;
516                                         c_tag[tptr] = '\0';
517                                         
518                                         if ((!strcmp(c_tag,tag)) && (idx == index))
519                                         {
520                                                 correct_tag = true;
521                                         }
522                                 }
523                         } while (c != ' ');
524                 }
525                 if (c == '"')
526                 {
527                         in_quotes = (!in_quotes);
528                 }
529                 
530                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
531                 {
532                         num_items++;
533                 }
534                 if ((c == '>') && (!in_quotes))
535                 {
536                         in_token = 0;
537                         if (correct_tag)
538                                 correct_tag = false;
539                         if (!strcmp(c_tag,tag))
540                         {
541                                 /* correct tag, but wrong index */
542                                 idx++;
543                         }
544                         c_tag[0] = '\0';
545                         buffer[0] = '\0';
546                         ptr = 0;
547                         tptr = 0;
548                 }
549                 if (c != '>')
550                 {
551                         if ((in_token) && (c != '\n') && (c != '\r'))
552                         {
553                                 buffer[ptr++] = c;
554                                 buffer[ptr] = '\0';
555                         }
556                 }
557         }
558         return num_items+1;
559 }
560
561
562
563 int ConfValueEnum(char* tag, std::stringstream* config)
564 {
565         return EnumConf(config,tag);
566 }
567
568
569
570 /* Retrieves a value from the config file. If there is more than one value of the specified
571  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
572  *
573  * ConfValue("oper","name",2,result);
574  */
575
576 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
577 {
578         int ptr = 0;
579         char buffer[65535], c_tag[MAXBUF], c, lastc;
580         int in_token, in_quotes, tptr, idx = 0;
581         char* key;
582
583         const char* buf = config->str().c_str();
584         long bptr = 0;
585         long len = config->str().length();
586         
587         ptr = 0;
588         in_token = 0;
589         in_quotes = 0;
590         lastc = '\0';
591         c_tag[0] = '\0';
592         buffer[0] = '\0';
593         while (bptr<len)
594         {
595                 lastc = c;
596                 c = buf[bptr++];
597                 // FIX: Treat tabs as spaces
598                 if (c == 9)
599                         c = 32;
600                 if ((c == '<') && (!in_quotes))
601                 {
602                         tptr = 0;
603                         in_token = 1;
604                         do {
605                                 c = buf[bptr++];
606                                 if (c != ' ')
607                                 {
608                                         c_tag[tptr++] = c;
609                                         c_tag[tptr] = '\0';
610                                 }
611                         // FIX: Tab can follow a tagname as well as space.
612                         } while ((c != ' ') && (c != 9));
613                 }
614                 if (c == '"')
615                 {
616                         in_quotes = (!in_quotes);
617                 }
618                 if ((c == '>') && (!in_quotes))
619                 {
620                         in_token = 0;
621                         if (idx == index)
622                         {
623                                 if (!strcmp(c_tag,tag))
624                                 {
625                                         if ((buffer) && (c_tag) && (var))
626                                         {
627                                                 key = strstr(buffer,var);
628                                                 if (!key)
629                                                 {
630                                                         /* value not found in tag */
631                                                         strcpy(result,"");
632                                                         return 0;
633                                                 }
634                                                 else
635                                                 {
636                                                         key+=strlen(var);
637                                                         while (key[0] !='"')
638                                                         {
639                                                                 if (!strlen(key))
640                                                                 {
641                                                                         /* missing quote */
642                                                                         strcpy(result,"");
643                                                                         return 0;
644                                                                 }
645                                                                 key++;
646                                                         }
647                                                         key++;
648                                                         for (unsigned j = 0; j < strlen(key); j++)
649                                                         {
650                                                                 if (key[j] == '"')
651                                                                 {
652                                                                         key[j] = '\0';
653                                                                 }
654                                                         }
655                                                         strlcpy(result,key,MAXBUF);
656                                                         return 1;
657                                                 }
658                                         }
659                                 }
660                         }
661                         if (!strcmp(c_tag,tag))
662                         {
663                                 /* correct tag, but wrong index */
664                                 idx++;
665                         }
666                         c_tag[0] = '\0';
667                         buffer[0] = '\0';
668                         ptr = 0;
669                         tptr = 0;
670                 }
671                 if (c != '>')
672                 {
673                         if ((in_token) && (c != '\n') && (c != '\r'))
674                         {
675                                 buffer[ptr++] = c;
676                                 buffer[ptr] = '\0';
677                         }
678                 }
679         }
680         strcpy(result,""); // value or its tag not found at all
681         return 0;
682 }
683
684
685
686 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
687 {
688         ReadConf(config, tag, var, index, result);
689         return 0;
690 }
691
692
693
694 // This will bind a socket to a port. It works for UDP/TCP
695 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
696 {
697         memset((char *)&server,0,sizeof(server));
698         struct in_addr addy;
699         inet_aton(addr,&addy);
700         server.sin_family = AF_INET;
701         if (!strcmp(addr,""))
702         {
703                 server.sin_addr.s_addr = htonl(INADDR_ANY);
704         }
705         else
706         {
707                 server.sin_addr = addy;
708         }
709         server.sin_port = htons(port);
710         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
711         {
712                 return(ERROR);
713         }
714         else
715         {
716                 listen(sockfd, MaxConn);
717                 return(TRUE);
718         }
719 }
720
721
722 // Open a TCP Socket
723 int OpenTCPSocket (void)
724 {
725         int sockfd;
726         int on = 1;
727         struct linger linger = { 0 };
728   
729         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
730                 return (ERROR);
731         else
732         {
733                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
734                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
735                 linger.l_onoff = 1;
736                 linger.l_linger = 1;
737                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
738                 return (sockfd);
739         }
740 }
741