]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Removed some old uneeded 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 #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[1mInspire Internet Relay Chat Server, compiled " __DATE__ " at " __TIME__ "\n");
67         printf("(C) ChatSpike Development team.\033[0;37m\n\n");
68         printf("Developers:\033[1m     Brain, FrostyCoolSlug\n");
69         printf("Documentation:\033[1m  FrostyCoolSlug, w00t\n");
70         printf("Testers:\033[1m        typobox43, piggles, Lord_Zathras, CC\n");
71         printf("Name concept:\033[1m   Lord_Zathras\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         /* close stdin, stdout, stderr */
113         freopen("/dev/null","w",stdout);
114         freopen("/dev/null","w",stderr);
115         
116         setpriority(PRIO_PROCESS,(int)getpid(),15); /* ircd sets to low process priority so it doesnt hog the box */
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, j, idx = 0;
343         char* key;
344
345         const char* buf = config->str().c_str();
346         long bptr = 0;
347         long len = strlen(buf);
348         
349         ptr = 0;
350         in_token = 0;
351         in_quotes = 0;
352         lastc = '\0';
353         while (bptr<len)
354         {
355                 lastc = c;
356                 c = buf[bptr++];
357                 if ((c == '#') && (lastc == '\n'))
358                 {
359                         while ((c != '\n') && (bptr<len))
360                         {
361                                 lastc = c;
362                                 c = buf[bptr++];
363                         }
364                 }
365                 if ((c == '<') && (!in_quotes))
366                 {
367                         tptr = 0;
368                         in_token = 1;
369                         do {
370                                 c = buf[bptr++];
371                                 if (c != ' ')
372                                 {
373                                         c_tag[tptr++] = c;
374                                         c_tag[tptr] = '\0';
375                                 }
376                         } while (c != ' ');
377                 }
378                 if (c == '"')
379                 {
380                         in_quotes = (!in_quotes);
381                 }
382                 if ((c == '>') && (!in_quotes))
383                 {
384                         in_token = 0;
385                         if (!strcmp(c_tag,tag))
386                         {
387                                 /* correct tag, but wrong index */
388                                 idx++;
389                         }
390                         c_tag[0] = '\0';
391                         buffer[0] = '\0';
392                         ptr = 0;
393                         tptr = 0;
394                 }
395                 if (c != '>')
396                 {
397                         if ((in_token) && (c != '\n') && (c != '\r'))
398                         {
399                                 buffer[ptr++] = c;
400                                 buffer[ptr] = '\0';
401                         }
402                 }
403         }
404         return idx;
405 }
406
407 /* Counts the number of values within a certain tag */
408
409 int EnumValues(std::stringstream *config, const char* tag, int index)
410 {
411         int ptr = 0;
412         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
413         int in_token, in_quotes, tptr, j, idx = 0;
414         char* key;
415         
416         bool correct_tag = false;
417         int num_items = 0;
418
419         const char* buf = config->str().c_str();
420         long bptr = 0;
421         long len = strlen(buf);
422         
423         ptr = 0;
424         in_token = 0;
425         in_quotes = 0;
426         lastc = '\0';
427         while (bptr<len)
428         {
429                 lastc = c;
430                 c = buf[bptr++];
431                 if ((c == '#') && (lastc == '\n'))
432                 {
433                         while ((c != '\n') && (bptr<len))
434                         {
435                                 lastc = c;
436                                 c = buf[bptr++];
437                         }
438                 }
439                 if ((c == '<') && (!in_quotes))
440                 {
441                         tptr = 0;
442                         in_token = 1;
443                         do {
444                                 c = buf[bptr++];
445                                 if (c != ' ')
446                                 {
447                                         c_tag[tptr++] = c;
448                                         c_tag[tptr] = '\0';
449                                         
450                                         if ((!strcmp(c_tag,tag)) && (idx == index))
451                                         {
452                                                 correct_tag = true;
453                                         }
454                                 }
455                         } while (c != ' ');
456                 }
457                 if (c == '"')
458                 {
459                         in_quotes = (!in_quotes);
460                 }
461                 
462                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
463                 {
464                         num_items++;
465                 }
466                 if ((c == '>') && (!in_quotes))
467                 {
468                         in_token = 0;
469                         if (correct_tag)
470                                 correct_tag = false;
471                         if (!strcmp(c_tag,tag))
472                         {
473                                 /* correct tag, but wrong index */
474                                 idx++;
475                         }
476                         c_tag[0] = '\0';
477                         buffer[0] = '\0';
478                         ptr = 0;
479                         tptr = 0;
480                 }
481                 if (c != '>')
482                 {
483                         if ((in_token) && (c != '\n') && (c != '\r'))
484                         {
485                                 buffer[ptr++] = c;
486                                 buffer[ptr] = '\0';
487                         }
488                 }
489         }
490         return num_items+1;
491 }
492
493
494
495 int ConfValueEnum(char* tag, std::stringstream* config)
496 {
497         return EnumConf(config,tag);
498 }
499
500
501
502 /* Retrieves a value from the config file. If there is more than one value of the specified
503  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
504  *
505  * ConfValue("oper","name",2,result);
506  */
507
508 int ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
509 {
510         int ptr = 0;
511         char buffer[65535], c_tag[MAXBUF], c, lastc;
512         int in_token, in_quotes, tptr, j, idx = 0;
513         char* key;
514
515         const char* buf = config->str().c_str();
516         long bptr = 0;
517         long len = strlen(buf);
518         
519         ptr = 0;
520         in_token = 0;
521         in_quotes = 0;
522         lastc = '\0';
523         c_tag[0] = '\0';
524         buffer[0] = '\0';
525         while (bptr<len)
526         {
527                 lastc = c;
528                 c = buf[bptr++];
529                 // FIX: Treat tabs as spaces
530                 if (c == 9)
531                         c = 32;
532                 if ((c == '<') && (!in_quotes))
533                 {
534                         tptr = 0;
535                         in_token = 1;
536                         do {
537                                 c = buf[bptr++];
538                                 if (c != ' ')
539                                 {
540                                         c_tag[tptr++] = c;
541                                         c_tag[tptr] = '\0';
542                                 }
543                         // FIX: Tab can follow a tagname as well as space.
544                         } while ((c != ' ') && (c != 9));
545                 }
546                 if (c == '"')
547                 {
548                         in_quotes = (!in_quotes);
549                 }
550                 if ((c == '>') && (!in_quotes))
551                 {
552                         in_token = 0;
553                         if (idx == index)
554                         {
555                                 if (!strcmp(c_tag,tag))
556                                 {
557                                         if ((buffer) && (c_tag) && (var))
558                                         {
559                                                 key = strstr(buffer,var);
560                                                 if (!key)
561                                                 {
562                                                         /* value not found in tag */
563                                                         strcpy(result,"");
564                                                         return 0;
565                                                 }
566                                                 else
567                                                 {
568                                                         key+=strlen(var);
569                                                         while (key[0] !='"')
570                                                         {
571                                                                 if (!strlen(key))
572                                                                 {
573                                                                         /* missing quote */
574                                                                         strcpy(result,"");
575                                                                         return 0;
576                                                                 }
577                                                                 key++;
578                                                         }
579                                                         key++;
580                                                         for (j = 0; j < strlen(key); j++)
581                                                         {
582                                                                 if (key[j] == '"')
583                                                                 {
584                                                                         key[j] = '\0';
585                                                                 }
586                                                         }
587                                                         strlcpy(result,key,MAXBUF);
588                                                         return 1;
589                                                 }
590                                         }
591                                 }
592                         }
593                         if (!strcmp(c_tag,tag))
594                         {
595                                 /* correct tag, but wrong index */
596                                 idx++;
597                         }
598                         c_tag[0] = '\0';
599                         buffer[0] = '\0';
600                         ptr = 0;
601                         tptr = 0;
602                 }
603                 if (c != '>')
604                 {
605                         if ((in_token) && (c != '\n') && (c != '\r'))
606                         {
607                                 buffer[ptr++] = c;
608                                 buffer[ptr] = '\0';
609                         }
610                 }
611         }
612         strcpy(result,""); // value or its tag not found at all
613         return 0;
614 }
615
616
617
618 int ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
619 {
620         ReadConf(config, tag, var, index, result);
621         return 0;
622 }
623
624
625
626 // This will bind a socket to a port. It works for UDP/TCP
627 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
628 {
629         bzero((char *)&server,sizeof(server));
630         struct in_addr addy;
631         inet_aton(addr,&addy);
632         server.sin_family = AF_INET;
633         if (!strcmp(addr,""))
634         {
635                 server.sin_addr.s_addr = htonl(INADDR_ANY);
636         }
637         else
638         {
639                 server.sin_addr = addy;
640         }
641         server.sin_port = htons(port);
642         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
643         {
644                 return(ERROR);
645         }
646         else
647         {
648                 listen(sockfd,5);
649                 return(TRUE);
650         }
651 }
652
653
654 // Open a TCP Socket
655 int OpenTCPSocket (void)
656 {
657         int sockfd;
658         int on = 1;
659         struct linger linger = { 0 };
660   
661         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
662                 return (ERROR);
663         else
664         {
665                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
666                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
667                 linger.l_onoff = 1;
668                 linger.l_linger = 1;
669                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
670                 return (sockfd);
671         }
672 }
673