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