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