]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Moving more stuff into class ServerConfig
[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 ServerConfig *Config;
35 extern int boundPortCount;
36 extern int openSockfd[MAXSOCKS];
37 extern time_t TIME;
38 std::vector<std::string> include_stack;
39
40 void WriteOpers(char* text, ...);
41
42 void Exit (int status)
43 {
44         if (Config->log_file)
45                 fclose(Config->log_file);
46         send_error("Server shutdown.");
47         exit (status);
48 }
49
50 void Killed(int status)
51 {
52         if (Config->log_file)
53                 fclose(Config->log_file);
54         send_error("Server terminated.");
55         exit(status);
56 }
57
58 void Rehash(int status)
59 {
60         WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
61         ReadConfig(false,NULL);
62 }
63
64
65
66 void Start (void)
67 {
68         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
69         printf("(C) ChatSpike Development team.\033[0m\n\n");
70         printf("Developers:\033[1;32m     Brain, FrostyCoolSlug\033[0m\n");
71         printf("Documentation:\033[1;32m  FrostyCoolSlug, w00t\033[0m\n");
72         printf("Testers:\033[1;32m        typobox43, piggles, Lord_Zathras, CC\033[0m\n");
73         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
74 }
75
76 void WritePID(std::string filename)
77 {
78         ofstream outfile(filename.c_str());
79         if (outfile.is_open())
80         {
81                 outfile << getpid();
82                 outfile.close();
83         }
84         else
85         {
86                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
87                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
88                 Exit(0);
89         }
90 }
91
92
93 int DaemonSeed (void)
94 {
95         int childpid;
96         signal (SIGALRM, SIG_IGN);
97         signal (SIGHUP, Rehash);
98         signal (SIGPIPE, SIG_IGN);
99         signal (SIGTERM, Exit);
100         signal (SIGSEGV, Error);
101         if ((childpid = fork ()) < 0)
102                 return (ERROR);
103         else if (childpid > 0)
104                 exit (0);
105         setsid ();
106         umask (007);
107         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
108
109         setpriority(PRIO_PROCESS,(int)getpid(),15);
110
111         if (Config->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 (unsigned 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
184         // empty lines are syntactically valid, as are comments
185         if (!(*buffer) || buffer[0] == '#')
186                 return "";
187
188         for (unsigned 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 (unsigned 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 int fgets_safe(char* buffer, size_t maxsize, FILE* &file)
286 {
287         char c_read = '\0';
288         unsigned int bufptr = 0;
289         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
290         {
291                 c_read = fgetc(file);
292                 if ((c_read != '\n') && (c_read != '\r'))
293                         buffer[bufptr++] = c_read;
294         }
295         buffer[bufptr] = '\0';
296         return bufptr;
297 }
298
299 bool LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
300 {
301         target->str("");
302         errorstream->str("");
303         long linenumber = 1;
304         // first, check that the file exists before we try to do anything with it
305         if (!FileExists(filename))
306         {
307                 *errorstream << "File " << filename << " not found." << endl;
308                 return false;
309         }
310         // Fix the chmod of the file to restrict it to the current user and group
311         chmod(filename,0600);
312         for (unsigned int t = 0; t < include_stack.size(); t++)
313         {
314                 if (std::string(filename) == include_stack[t])
315                 {
316                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
317                         return false;
318                 }
319         }
320         include_stack.push_back(filename);
321         // now open it
322         FILE* conf = fopen(filename,"r");
323         char buffer[MAXBUF];
324         if (conf)
325         {
326                 while (!feof(conf))
327                 {
328                         if (fgets_safe(buffer, MAXBUF, conf))
329                         {
330                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
331                                 {
332                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
333                                         {
334                                                 if (!strncmp(buffer,"<include file=\"",15))
335                                                 {
336                                                         char* buf = buffer;
337                                                         char confpath[10240],newconf[10240];
338                                                         // include file directive
339                                                         buf += 15;      // advance to filename
340                                                         for (unsigned int j = 0; j < strlen(buf); j++)
341                                                         {
342                                                                 if (buf[j] == '\\')
343                                                                         buf[j] = '/';
344                                                                 if (buf[j] == '"')
345                                                                 {
346                                                                         buf[j] = '\0';
347                                                                         break;
348                                                                 }
349                                                         }
350                                                         log(DEFAULT,"Opening included file '%s'",buf);
351                                                         if (*buf != '/')
352                                                         {
353                                                                 strlcpy(confpath,CONFIG_FILE,10240);
354                                                                 if (strstr(confpath,"/inspircd.conf"))
355                                                                 {
356                                                                         // leaves us with just the path
357                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
358                                                                 }
359                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
360                                                         }
361                                                         else snprintf(newconf,10240,"%s",buf);
362                                                         std::stringstream merge(stringstream::in | stringstream::out);
363                                                         // recursively call LoadConf and get the new data, use the same errorstream
364                                                         if (LoadConf(newconf, &merge, errorstream))
365                                                         {
366                                                                 // append to the end of the file
367                                                                 std::string newstuff = merge.str();
368                                                                 *target << newstuff;
369                                                         }
370                                                         else
371                                                         {
372                                                                 // the error propogates up to its parent recursively
373                                                                 // causing the config reader to bail at the top level.
374                                                                 fclose(conf);
375                                                                 return false;
376                                                         }
377                                                 }
378                                                 else
379                                                 {
380                                                         bool error = false;
381                                                         std::string data = ConfProcess(buffer,linenumber++,errorstream,error,filename);
382                                                         if (error)
383                                                         {
384                                                                 return false;
385                                                         }
386                                                         *target << data;
387                                                 }
388                                         }
389                                         else linenumber++;
390                                 }
391                         }
392                 }
393                 fclose(conf);
394         }
395         target->seekg(0);
396         return true;
397 }
398
399 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
400
401 int EnumConf(std::stringstream *config, const char* tag)
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         const char* buf = config->str().c_str();
408         long bptr = 0;
409         long len = strlen(buf);
410         
411         ptr = 0;
412         in_token = 0;
413         in_quotes = 0;
414         lastc = '\0';
415         while (bptr<len)
416         {
417                 lastc = c;
418                 c = buf[bptr++];
419                 if ((c == '#') && (lastc == '\n'))
420                 {
421                         while ((c != '\n') && (bptr<len))
422                         {
423                                 lastc = c;
424                                 c = buf[bptr++];
425                         }
426                 }
427                 if ((c == '<') && (!in_quotes))
428                 {
429                         tptr = 0;
430                         in_token = 1;
431                         do {
432                                 c = buf[bptr++];
433                                 if (c != ' ')
434                                 {
435                                         c_tag[tptr++] = c;
436                                         c_tag[tptr] = '\0';
437                                 }
438                         } while (c != ' ');
439                 }
440                 if (c == '"')
441                 {
442                         in_quotes = (!in_quotes);
443                 }
444                 if ((c == '>') && (!in_quotes))
445                 {
446                         in_token = 0;
447                         if (!strcmp(c_tag,tag))
448                         {
449                                 /* correct tag, but wrong index */
450                                 idx++;
451                         }
452                         c_tag[0] = '\0';
453                         buffer[0] = '\0';
454                         ptr = 0;
455                         tptr = 0;
456                 }
457                 if (c != '>')
458                 {
459                         if ((in_token) && (c != '\n') && (c != '\r'))
460                         {
461                                 buffer[ptr++] = c;
462                                 buffer[ptr] = '\0';
463                         }
464                 }
465         }
466         return idx;
467 }
468
469 /* Counts the number of values within a certain tag */
470
471 int EnumValues(std::stringstream *config, const char* tag, int index)
472 {
473         int ptr = 0;
474         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
475         int in_token, in_quotes, tptr, idx = 0;
476         
477         bool correct_tag = false;
478         int num_items = 0;
479
480         const char* buf = config->str().c_str();
481         long bptr = 0;
482         long len = strlen(buf);
483         
484         ptr = 0;
485         in_token = 0;
486         in_quotes = 0;
487         lastc = '\0';
488         while (bptr<len)
489         {
490                 lastc = c;
491                 c = buf[bptr++];
492                 if ((c == '#') && (lastc == '\n'))
493                 {
494                         while ((c != '\n') && (bptr<len))
495                         {
496                                 lastc = c;
497                                 c = buf[bptr++];
498                         }
499                 }
500                 if ((c == '<') && (!in_quotes))
501                 {
502                         tptr = 0;
503                         in_token = 1;
504                         do {
505                                 c = buf[bptr++];
506                                 if (c != ' ')
507                                 {
508                                         c_tag[tptr++] = c;
509                                         c_tag[tptr] = '\0';
510                                         
511                                         if ((!strcmp(c_tag,tag)) && (idx == index))
512                                         {
513                                                 correct_tag = true;
514                                         }
515                                 }
516                         } while (c != ' ');
517                 }
518                 if (c == '"')
519                 {
520                         in_quotes = (!in_quotes);
521                 }
522                 
523                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
524                 {
525                         num_items++;
526                 }
527                 if ((c == '>') && (!in_quotes))
528                 {
529                         in_token = 0;
530                         if (correct_tag)
531                                 correct_tag = false;
532                         if (!strcmp(c_tag,tag))
533                         {
534                                 /* correct tag, but wrong index */
535                                 idx++;
536                         }
537                         c_tag[0] = '\0';
538                         buffer[0] = '\0';
539                         ptr = 0;
540                         tptr = 0;
541                 }
542                 if (c != '>')
543                 {
544                         if ((in_token) && (c != '\n') && (c != '\r'))
545                         {
546                                 buffer[ptr++] = c;
547                                 buffer[ptr] = '\0';
548                         }
549                 }
550         }
551         return num_items+1;
552 }
553
554
555
556 int ConfValueEnum(char* tag, std::stringstream* config)
557 {
558         return EnumConf(config,tag);
559 }
560
561
562
563 /* Retrieves a value from the config file. If there is more than one value of the specified
564  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
565  *
566  * ConfValue("oper","name",2,result);
567  */
568
569 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
570 {
571         int ptr = 0;
572         char buffer[65535], c_tag[MAXBUF], c, lastc;
573         int in_token, in_quotes, tptr, idx = 0;
574         char* key;
575
576         const char* buf = config->str().c_str();
577         long bptr = 0;
578         long len = config->str().length();
579         
580         ptr = 0;
581         in_token = 0;
582         in_quotes = 0;
583         lastc = '\0';
584         c_tag[0] = '\0';
585         buffer[0] = '\0';
586         while (bptr<len)
587         {
588                 lastc = c;
589                 c = buf[bptr++];
590                 // FIX: Treat tabs as spaces
591                 if (c == 9)
592                         c = 32;
593                 if ((c == '<') && (!in_quotes))
594                 {
595                         tptr = 0;
596                         in_token = 1;
597                         do {
598                                 c = buf[bptr++];
599                                 if (c != ' ')
600                                 {
601                                         c_tag[tptr++] = c;
602                                         c_tag[tptr] = '\0';
603                                 }
604                         // FIX: Tab can follow a tagname as well as space.
605                         } while ((c != ' ') && (c != 9));
606                 }
607                 if (c == '"')
608                 {
609                         in_quotes = (!in_quotes);
610                 }
611                 if ((c == '>') && (!in_quotes))
612                 {
613                         in_token = 0;
614                         if (idx == index)
615                         {
616                                 if (!strcmp(c_tag,tag))
617                                 {
618                                         if ((buffer) && (c_tag) && (var))
619                                         {
620                                                 key = strstr(buffer,var);
621                                                 if (!key)
622                                                 {
623                                                         /* value not found in tag */
624                                                         strcpy(result,"");
625                                                         return 0;
626                                                 }
627                                                 else
628                                                 {
629                                                         key+=strlen(var);
630                                                         while (key[0] !='"')
631                                                         {
632                                                                 if (!strlen(key))
633                                                                 {
634                                                                         /* missing quote */
635                                                                         strcpy(result,"");
636                                                                         return 0;
637                                                                 }
638                                                                 key++;
639                                                         }
640                                                         key++;
641                                                         for (unsigned j = 0; j < strlen(key); j++)
642                                                         {
643                                                                 if (key[j] == '"')
644                                                                 {
645                                                                         key[j] = '\0';
646                                                                 }
647                                                         }
648                                                         strlcpy(result,key,MAXBUF);
649                                                         return 1;
650                                                 }
651                                         }
652                                 }
653                         }
654                         if (!strcmp(c_tag,tag))
655                         {
656                                 /* correct tag, but wrong index */
657                                 idx++;
658                         }
659                         c_tag[0] = '\0';
660                         buffer[0] = '\0';
661                         ptr = 0;
662                         tptr = 0;
663                 }
664                 if (c != '>')
665                 {
666                         if ((in_token) && (c != '\n') && (c != '\r'))
667                         {
668                                 buffer[ptr++] = c;
669                                 buffer[ptr] = '\0';
670                         }
671                 }
672         }
673         strcpy(result,""); // value or its tag not found at all
674         return 0;
675 }
676
677
678
679 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
680 {
681         ReadConf(config, tag, var, index, result);
682         return 0;
683 }
684
685
686
687 // This will bind a socket to a port. It works for UDP/TCP
688 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
689 {
690         memset((char *)&server,0,sizeof(server));
691         struct in_addr addy;
692         inet_aton(addr,&addy);
693         server.sin_family = AF_INET;
694         if (!strcmp(addr,""))
695         {
696                 server.sin_addr.s_addr = htonl(INADDR_ANY);
697         }
698         else
699         {
700                 server.sin_addr = addy;
701         }
702         server.sin_port = htons(port);
703         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
704         {
705                 return(ERROR);
706         }
707         else
708         {
709                 listen(sockfd, Config->MaxConn);
710                 return(TRUE);
711         }
712 }
713
714
715 // Open a TCP Socket
716 int OpenTCPSocket (void)
717 {
718         int sockfd;
719         int on = 1;
720         struct linger linger = { 0 };
721   
722         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
723                 return (ERROR);
724         else
725         {
726                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
727                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
728                 linger.l_onoff = 1;
729                 linger.l_linger = 1;
730                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
731                 return (sockfd);
732         }
733 }