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