]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
64b74a2b94534aafeef4f942ea2c484bf4ef2390
[user/henk/code/inspircd.git] / src / inspircd_io.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 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 "inspstring.h"
31 #include "helperfuncs.h"
32 #include "userprocess.h"
33 #include "xline.h"
34
35 extern ServerConfig *Config;
36 extern InspIRCd* ServerInstance;
37 extern int openSockfd[MAXSOCKS];
38 extern time_t TIME;
39
40
41 ServerConfig::ServerConfig()
42 {
43         this->ClearStack();
44         *ServerName = *Network = *ServerDesc = *AdminName = '\0';
45         *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
46         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
47         *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
48         log_file = NULL;
49         nofork = false;
50         unlimitcore = false;
51         AllowHalfop = true;
52         dns_timeout = 5;
53         NetBufferSize = 10240;
54         SoftLimit = MAXCLIENTS;
55         MaxConn = SOMAXCONN;
56         MaxWhoResults = 100;
57         debugging = 0;
58         LogLevel = DEFAULT;
59         DieDelay = 5;
60 }
61
62 void ServerConfig::ClearStack()
63 {
64         include_stack.clear();
65 }
66
67 Module* ServerConfig::GetIOHook(int port)
68 {
69         std::map<int,Module*>::iterator x = IOHookModule.find(port);
70         return (x != IOHookModule.end() ? x->second : NULL);
71 }
72
73 bool ServerConfig::AddIOHook(int port, Module* iomod)
74 {
75         if (!GetIOHook(port))
76         {
77                 IOHookModule[port] = iomod;
78                 return true;
79         }
80         return false;
81 }
82
83 bool ServerConfig::DelIOHook(int port)
84 {
85         std::map<int,Module*>::iterator x = IOHookModule.find(port);
86         if (x != IOHookModule.end())
87         {
88                 IOHookModule.erase(x);
89                 return true;
90         }
91         return false;
92 }
93
94 void ServerConfig::Read(bool bail, userrec* user)
95 {
96         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
97         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
98         ConnectClass c;
99         std::stringstream errstr;
100         include_stack.clear();
101
102         if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
103         {
104                 errstr.seekg(0);
105                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
106                 if (bail)
107                 {
108                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
109                         Exit(0);
110                 }
111                 else
112                 {
113                         char dataline[1024];
114                         if (user)
115                         {
116                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
117                                 while (!errstr.eof())
118                                 {
119                                         errstr.getline(dataline,1024);
120                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
121                                 }
122                         }
123                         else
124                         {
125                                 WriteOpers("There were errors in the configuration file:");
126                                 while (!errstr.eof())
127                                 {
128                                         errstr.getline(dataline,1024);
129                                         WriteOpers(dataline);
130                                 }
131                         }
132                         return;
133                 }
134         }
135
136         ConfValue("server","name",0,Config->ServerName,&Config->config_f);
137         ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
138         ConfValue("server","network",0,Config->Network,&Config->config_f);
139         ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
140         ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
141         ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
142         ConfValue("files","motd",0,Config->motd,&Config->config_f);
143         ConfValue("files","rules",0,Config->rules,&Config->config_f);
144         ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
145         ConfValue("power","pause",0,pauseval,&Config->config_f);
146         ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
147         ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
148         ConfValue("die","value",0,Config->DieValue,&Config->config_f);
149         ConfValue("options","loglevel",0,dbg,&Config->config_f);
150         ConfValue("options","netbuffersize",0,NB,&Config->config_f);
151         ConfValue("options","maxwho",0,MW,&Config->config_f);
152         ConfValue("options","allowhalfop",0,AH,&Config->config_f);
153         ConfValue("options","allowprotect",0,AP,&Config->config_f);
154         ConfValue("options","allowfounder",0,AF,&Config->config_f);
155         ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
156         ConfValue("dns","timeout",0,DNT,&Config->config_f);
157         ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
158         ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
159         ConfValue("options","somaxconn",0,MCON,&Config->config_f);
160         ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
161         ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
162         ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
163
164         Config->SoftLimit = atoi(SLIMT);
165         if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
166         {
167                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
168                 Config->SoftLimit = MAXCLIENTS;
169         }
170         Config->MaxConn = atoi(MCON);
171         if (Config->MaxConn > SOMAXCONN)
172                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
173         Config->NetBufferSize = atoi(NB);
174         Config->MaxWhoResults = atoi(MW);
175         Config->dns_timeout = atoi(DNT);
176         if (!Config->dns_timeout)
177                 Config->dns_timeout = 5;
178         if (!Config->MaxConn)
179                 Config->MaxConn = SOMAXCONN;
180         if (!*Config->DNSServer)
181                 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
182         if (!*Config->ModPath)
183                 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
184         Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
185         if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
186         {
187                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
188                 Config->NetBufferSize = 10240;
189         }
190         if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
191         {
192                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
193                 Config->MaxWhoResults = 128;
194         }
195         Config->LogLevel = DEFAULT;
196         if (!strcmp(dbg,"debug"))
197         {
198                 Config->LogLevel = DEBUG;
199                 Config->debugging = 1;
200         }
201         if (!strcmp(dbg,"verbose"))
202                 Config->LogLevel = VERBOSE;
203         if (!strcmp(dbg,"default"))
204                 Config->LogLevel = DEFAULT;
205         if (!strcmp(dbg,"sparse"))
206                 Config->LogLevel = SPARSE;
207         if (!strcmp(dbg,"none"))
208                 Config->LogLevel = NONE;
209
210         readfile(Config->MOTD,Config->motd);
211         log(DEFAULT,"Reading message of the day...");
212         readfile(Config->RULES,Config->rules);
213         log(DEFAULT,"Reading connect classes...");
214         Classes.clear();
215         for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
216         {
217                 *Value = 0;
218                 ConfValue("connect","allow",i,Value,&Config->config_f);
219                 ConfValue("connect","timeout",i,timeout,&Config->config_f);
220                 ConfValue("connect","flood",i,flood,&Config->config_f);
221                 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
222                 ConfValue("connect","threshold",i,thold,&Config->config_f);
223                 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
224                 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
225                 if (*Value)
226                 {
227                         c.host = Value;
228                         c.type = CC_ALLOW;
229                         strlcpy(Value,"",MAXBUF);
230                         ConfValue("connect","password",i,Value,&Config->config_f);
231                         c.pass = Value;
232                         c.registration_timeout = 90; // default is 2 minutes
233                         c.pingtime = 120;
234                         c.flood = atoi(flood);
235                         c.threshold = 5;
236                         c.sendqmax = 262144; // 256k
237                         c.recvqmax = 4096;   // 4k
238                         if (atoi(thold)>0)
239                         {
240                                 c.threshold = atoi(thold);
241                         }
242                         if (atoi(sqmax)>0)
243                         {
244                                 c.sendqmax = atoi(sqmax);
245                         }
246                         if (atoi(rqmax)>0)
247                         {
248                                 c.recvqmax = atoi(rqmax);
249                         }
250                         if (atoi(timeout)>0)
251                         {
252                                 c.registration_timeout = atoi(timeout);
253                         }
254                         if (atoi(pfreq)>0)
255                         {
256                                 c.pingtime = atoi(pfreq);
257                         }
258                         Classes.push_back(c);
259                 }
260                 else
261                 {
262                         ConfValue("connect","deny",i,Value,&Config->config_f);
263                         c.host = Value;
264                         c.type = CC_DENY;
265                         Classes.push_back(c);
266                         log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
267                 }
268
269         }
270         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
271         read_xline_defaults();
272         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
273         apply_lines(APPLY_ALL);
274
275         ConfValue("pid","file",0,Config->PID,&Config->config_f);
276         // write once here, to try it out and make sure its ok
277         WritePID(Config->PID);
278
279         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
280         if (!bail)
281         {
282                 log(DEFAULT,"Adding and removing modules due to rehash...");
283
284                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
285
286                 // store the old module names
287                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
288                 {
289                         old_module_names.push_back(*t);
290                 }
291
292                 // get the new module names
293                 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
294                 {
295                         ConfValue("module","name",count2,Value,&Config->config_f);
296                         new_module_names.push_back(Value);
297                 }
298
299                 // now create a list of new modules that are due to be loaded
300                 // and a seperate list of modules which are due to be unloaded
301                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
302                 {
303                         bool added = true;
304                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
305                         {
306                                 if (*old == *_new)
307                                         added = false;
308                         }
309                         if (added)
310                                 added_modules.push_back(*_new);
311                 }
312                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
313                 {
314                         bool removed = true;
315                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
316                         {
317                                 if (*newm == *oldm)
318                                         removed = false;
319                         }
320                         if (removed)
321                                 removed_modules.push_back(*oldm);
322                 }
323                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
324                 // to be removed.
325                 int rem = 0, add = 0;
326                 if (!removed_modules.empty())
327                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
328                 {
329                         if (ServerInstance->UnloadModule(removing->c_str()))
330                         {
331                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
332                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
333                                 rem++;
334                         }
335                         else
336                         {
337                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
338                         }
339                 }
340                 if (!added_modules.empty())
341                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
342                 {
343                         if (ServerInstance->LoadModule(adding->c_str()))
344                         {
345                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
346                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
347                                 add++;
348                         }
349                         else
350                         {
351                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
352                         }
353                 }
354                 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
355                                                                                                         (unsigned long)add,(unsigned long)added_modules.size());
356         }
357 }
358
359
360 void Exit (int status)
361 {
362         if (Config->log_file)
363                 fclose(Config->log_file);
364         send_error("Server shutdown.");
365         exit (status);
366 }
367
368 void Killed(int status)
369 {
370         if (Config->log_file)
371                 fclose(Config->log_file);
372         send_error("Server terminated.");
373         exit(status);
374 }
375
376 void Rehash(int status)
377 {
378         WriteOpers("Rehashing config file %s due to SIGHUP",CONFIG_FILE);
379         fclose(Config->log_file);
380         OpenLog(NULL,NULL);
381         Config->Read(false,NULL);
382 }
383
384
385
386 void Start (void)
387 {
388         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
389         printf("(C) ChatSpike Development team.\033[0m\n\n");
390         printf("Developers:\033[1;32m     Brain, FrostyCoolSlug\033[0m\n");
391         printf("Documentation:\033[1;32m  FrostyCoolSlug, w00t\033[0m\n");
392         printf("Testers:\033[1;32m        typobox43, piggles, Lord_Zathras, CC\033[0m\n");
393         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
394 }
395
396 void WritePID(std::string filename)
397 {
398         ofstream outfile(filename.c_str());
399         if (outfile.is_open())
400         {
401                 outfile << getpid();
402                 outfile.close();
403         }
404         else
405         {
406                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
407                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
408                 Exit(0);
409         }
410 }
411
412 void SetSignals()
413 {
414         signal (SIGALRM, SIG_IGN);
415         signal (SIGHUP, Rehash);
416         signal (SIGPIPE, SIG_IGN);
417         signal (SIGTERM, Exit);
418         signal (SIGSEGV, Error);
419 }
420
421
422 int DaemonSeed (void)
423 {
424         int childpid;
425         if ((childpid = fork ()) < 0)
426                 return (ERROR);
427         else if (childpid > 0)
428                 exit (0);
429         setsid ();
430         umask (007);
431         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
432
433         setpriority(PRIO_PROCESS,(int)getpid(),15);
434
435         if (Config->unlimitcore)
436         {
437                 rlimit rl;
438                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
439                 {
440                         log(DEFAULT,"Failed to getrlimit()!");
441                         return(FALSE);
442                 }
443                 else
444                 {
445                         rl.rlim_cur = rl.rlim_max;
446                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
447                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
448                 }
449         }
450   
451         return (TRUE);
452 }
453
454
455 /* Make Sure Modules Are Avaliable!
456  * (BugFix By Craig.. See? I do work! :p)
457  * Modified by brain, requires const char*
458  * to work with other API functions
459  */
460
461 bool FileExists (const char* file)
462 {
463         FILE *input;
464         if ((input = fopen (file, "r")) == NULL)
465         {
466                 return(false);
467         }
468         else
469         {
470                 fclose (input);
471                 return(true);
472         }
473 }
474
475 /* ConfProcess does the following things to a config line in the following order:
476  *
477  * Processes the line for syntax errors as shown below
478  *      (1) Line void of quotes or equals (a malformed, illegal tag format)
479  *      (2) Odd number of quotes on the line indicating a missing quote
480  *      (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
481  *      (4) Spaces between the opening bracket (<) and the keyword
482  *      (5) Spaces between a keyword and an equals sign
483  *      (6) Spaces between an equals sign and a quote
484  * Removes trailing spaces
485  * Removes leading spaces
486  * Converts tabs to spaces
487  * Turns multiple spaces that are outside of quotes into single spaces
488  */
489
490 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
491 {
492         long number_of_quotes = 0;
493         long number_of_equals = 0;
494         bool has_open_bracket = false;
495         bool in_quotes = false;
496         error = false;
497         if (!buffer)
498         {
499                 return "";
500         }
501         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
502         for (unsigned int d = 0; d < strlen(buffer); d++)
503                 if ((buffer[d]) == 9)
504                         buffer[d] = ' ';
505         while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
506         while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
507
508         // empty lines are syntactically valid, as are comments
509         if (!(*buffer) || buffer[0] == '#')
510                 return "";
511
512         for (unsigned int c = 0; c < strlen(buffer); c++)
513         {
514                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
515                 // search and replace later :)
516                 if ((!in_quotes) && (buffer[c] == ' '))
517                         buffer[c] = '\xA0';
518                 if ((buffer[c] == '<') && (!in_quotes))
519                 {
520                         has_open_bracket = true;
521                         if (strlen(buffer) == 1)
522                         {
523                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
524                                 error = true;
525                                 return "";
526                         }
527                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
528                         {
529                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
530                                 error = true;
531                                 return "";
532                         }
533                 }
534                 if (buffer[c] == '"')
535                 {
536                         number_of_quotes++;
537                         in_quotes = (!in_quotes);
538                 }
539                 if ((buffer[c] == '=') && (!in_quotes))
540                 {
541                         number_of_equals++;
542                         if (strlen(buffer) == c)
543                         {
544                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
545                                 error = true;
546                                 return "";
547                         }
548                         else if (buffer[c+1] != '"')
549                         {
550                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
551                                 error = true;
552                                 return "";
553                         }
554                         else if (!c)
555                         {
556                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
557                                 error = true;
558                                 return "";
559                         }
560                         else if (buffer[c-1] == '\xA0')
561                         {
562                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
563                                 error = true;
564                                 return "";
565                         }
566                 }
567         }
568         // no quotes, and no equals. something freaky.
569         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
570         {
571                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
572                 error = true;
573                 return "";
574         }
575         // odd number of quotes. thats just wrong.
576         if ((number_of_quotes % 2) != 0)
577         {
578                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
579                 error = true;
580                 return "";
581         }
582         if (number_of_equals < (number_of_quotes/2))
583         {
584                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
585         }
586         if (number_of_equals > (number_of_quotes/2))
587         {
588                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
589         }
590
591         std::string parsedata = buffer;
592         // turn multispace into single space
593         while (parsedata.find("\xA0\xA0") != std::string::npos)
594         {
595                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
596         }
597
598         // turn our hardspace back into softspace
599         for (unsigned int d = 0; d < parsedata.length(); d++)
600         {
601                 if (parsedata[d] == '\xA0')
602                         parsedata[d] = ' ';
603         }
604
605         // and we're done, the line is fine!
606         return parsedata;
607 }
608
609 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
610 {
611         char c_read = '\0';
612         unsigned int bufptr = 0;
613         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
614         {
615                 c_read = fgetc(file);
616                 if ((c_read != '\n') && (c_read != '\r'))
617                         buffer[bufptr++] = c_read;
618         }
619         buffer[bufptr] = '\0';
620         return bufptr;
621 }
622
623 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
624 {
625         target->str("");
626         errorstream->str("");
627         long linenumber = 1;
628         // first, check that the file exists before we try to do anything with it
629         if (!FileExists(filename))
630         {
631                 *errorstream << "File " << filename << " not found." << endl;
632                 return false;
633         }
634         // Fix the chmod of the file to restrict it to the current user and group
635         chmod(filename,0600);
636         for (unsigned int t = 0; t < include_stack.size(); t++)
637         {
638                 if (std::string(filename) == include_stack[t])
639                 {
640                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
641                         return false;
642                 }
643         }
644         include_stack.push_back(filename);
645         // now open it
646         FILE* conf = fopen(filename,"r");
647         char buffer[MAXBUF];
648         if (conf)
649         {
650                 while (!feof(conf))
651                 {
652                         if (fgets_safe(buffer, MAXBUF, conf))
653                         {
654                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
655                                 {
656                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
657                                         {
658                                                 if (!strncmp(buffer,"<include file=\"",15))
659                                                 {
660                                                         char* buf = buffer;
661                                                         char confpath[10240],newconf[10240];
662                                                         // include file directive
663                                                         buf += 15;      // advance to filename
664                                                         for (unsigned int j = 0; j < strlen(buf); j++)
665                                                         {
666                                                                 if (buf[j] == '\\')
667                                                                         buf[j] = '/';
668                                                                 if (buf[j] == '"')
669                                                                 {
670                                                                         buf[j] = '\0';
671                                                                         break;
672                                                                 }
673                                                         }
674                                                         log(DEFAULT,"Opening included file '%s'",buf);
675                                                         if (*buf != '/')
676                                                         {
677                                                                 strlcpy(confpath,CONFIG_FILE,10240);
678                                                                 if (strstr(confpath,"/inspircd.conf"))
679                                                                 {
680                                                                         // leaves us with just the path
681                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
682                                                                 }
683                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
684                                                         }
685                                                         else strlcpy(newconf,buf,10240);
686                                                         std::stringstream merge(stringstream::in | stringstream::out);
687                                                         // recursively call LoadConf and get the new data, use the same errorstream
688                                                         if (LoadConf(newconf, &merge, errorstream))
689                                                         {
690                                                                 // append to the end of the file
691                                                                 std::string newstuff = merge.str();
692                                                                 *target << newstuff;
693                                                         }
694                                                         else
695                                                         {
696                                                                 // the error propogates up to its parent recursively
697                                                                 // causing the config reader to bail at the top level.
698                                                                 fclose(conf);
699                                                                 return false;
700                                                         }
701                                                 }
702                                                 else
703                                                 {
704                                                         bool error = false;
705                                                         std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
706                                                         if (error)
707                                                         {
708                                                                 return false;
709                                                         }
710                                                         *target << data;
711                                                 }
712                                         }
713                                         else linenumber++;
714                                 }
715                         }
716                 }
717                 fclose(conf);
718         }
719         target->seekg(0);
720         return true;
721 }
722
723 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
724
725 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
726 {
727         int ptr = 0;
728         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
729         int in_token, in_quotes, tptr, idx = 0;
730
731         const char* buf = config->str().c_str();
732         long bptr = 0;
733         long len = strlen(buf);
734         
735         ptr = 0;
736         in_token = 0;
737         in_quotes = 0;
738         lastc = '\0';
739         while (bptr<len)
740         {
741                 lastc = c;
742                 c = buf[bptr++];
743                 if ((c == '#') && (lastc == '\n'))
744                 {
745                         while ((c != '\n') && (bptr<len))
746                         {
747                                 lastc = c;
748                                 c = buf[bptr++];
749                         }
750                 }
751                 if ((c == '<') && (!in_quotes))
752                 {
753                         tptr = 0;
754                         in_token = 1;
755                         do {
756                                 c = buf[bptr++];
757                                 if (c != ' ')
758                                 {
759                                         c_tag[tptr++] = c;
760                                         c_tag[tptr] = '\0';
761                                 }
762                         } while (c != ' ');
763                 }
764                 if (c == '"')
765                 {
766                         in_quotes = (!in_quotes);
767                 }
768                 if ((c == '>') && (!in_quotes))
769                 {
770                         in_token = 0;
771                         if (!strcmp(c_tag,tag))
772                         {
773                                 /* correct tag, but wrong index */
774                                 idx++;
775                         }
776                         c_tag[0] = '\0';
777                         buffer[0] = '\0';
778                         ptr = 0;
779                         tptr = 0;
780                 }
781                 if (c != '>')
782                 {
783                         if ((in_token) && (c != '\n') && (c != '\r'))
784                         {
785                                 buffer[ptr++] = c;
786                                 buffer[ptr] = '\0';
787                         }
788                 }
789         }
790         return idx;
791 }
792
793 /* Counts the number of values within a certain tag */
794
795 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
796 {
797         int ptr = 0;
798         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
799         int in_token, in_quotes, tptr, idx = 0;
800         
801         bool correct_tag = false;
802         int num_items = 0;
803
804         const char* buf = config->str().c_str();
805         long bptr = 0;
806         long len = strlen(buf);
807         
808         ptr = 0;
809         in_token = 0;
810         in_quotes = 0;
811         lastc = '\0';
812         while (bptr<len)
813         {
814                 lastc = c;
815                 c = buf[bptr++];
816                 if ((c == '#') && (lastc == '\n'))
817                 {
818                         while ((c != '\n') && (bptr<len))
819                         {
820                                 lastc = c;
821                                 c = buf[bptr++];
822                         }
823                 }
824                 if ((c == '<') && (!in_quotes))
825                 {
826                         tptr = 0;
827                         in_token = 1;
828                         do {
829                                 c = buf[bptr++];
830                                 if (c != ' ')
831                                 {
832                                         c_tag[tptr++] = c;
833                                         c_tag[tptr] = '\0';
834                                         
835                                         if ((!strcmp(c_tag,tag)) && (idx == index))
836                                         {
837                                                 correct_tag = true;
838                                         }
839                                 }
840                         } while (c != ' ');
841                 }
842                 if (c == '"')
843                 {
844                         in_quotes = (!in_quotes);
845                 }
846                 
847                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
848                 {
849                         num_items++;
850                 }
851                 if ((c == '>') && (!in_quotes))
852                 {
853                         in_token = 0;
854                         if (correct_tag)
855                                 correct_tag = false;
856                         if (!strcmp(c_tag,tag))
857                         {
858                                 /* correct tag, but wrong index */
859                                 idx++;
860                         }
861                         c_tag[0] = '\0';
862                         buffer[0] = '\0';
863                         ptr = 0;
864                         tptr = 0;
865                 }
866                 if (c != '>')
867                 {
868                         if ((in_token) && (c != '\n') && (c != '\r'))
869                         {
870                                 buffer[ptr++] = c;
871                                 buffer[ptr] = '\0';
872                         }
873                 }
874         }
875         return num_items+1;
876 }
877
878
879
880 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
881 {
882         return EnumConf(config,tag);
883 }
884
885
886
887 /* Retrieves a value from the config file. If there is more than one value of the specified
888  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
889  *
890  * ConfValue("oper","name",2,result);
891  */
892
893 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
894 {
895         int ptr = 0;
896         char buffer[65535], c_tag[MAXBUF], c, lastc;
897         int in_token, in_quotes, tptr, idx = 0;
898         char* key;
899
900         const char* buf = config->str().c_str();
901         long bptr = 0;
902         long len = config->str().length();
903         
904         ptr = 0;
905         in_token = 0;
906         in_quotes = 0;
907         lastc = '\0';
908         c_tag[0] = '\0';
909         buffer[0] = '\0';
910         while (bptr<len)
911         {
912                 lastc = c;
913                 c = buf[bptr++];
914                 // FIX: Treat tabs as spaces
915                 if (c == 9)
916                         c = 32;
917                 if ((c == '<') && (!in_quotes))
918                 {
919                         tptr = 0;
920                         in_token = 1;
921                         do {
922                                 c = buf[bptr++];
923                                 if (c != ' ')
924                                 {
925                                         c_tag[tptr++] = c;
926                                         c_tag[tptr] = '\0';
927                                 }
928                         // FIX: Tab can follow a tagname as well as space.
929                         } while ((c != ' ') && (c != 9));
930                 }
931                 if (c == '"')
932                 {
933                         in_quotes = (!in_quotes);
934                 }
935                 if ((c == '>') && (!in_quotes))
936                 {
937                         in_token = 0;
938                         if (idx == index)
939                         {
940                                 if (!strcmp(c_tag,tag))
941                                 {
942                                         if ((buffer) && (c_tag) && (var))
943                                         {
944                                                 key = strstr(buffer,var);
945                                                 if (!key)
946                                                 {
947                                                         /* value not found in tag */
948                                                         *result = 0;
949                                                         return 0;
950                                                 }
951                                                 else
952                                                 {
953                                                         key+=strlen(var);
954                                                         while (*key !='"')
955                                                         {
956                                                                 if (!*key)
957                                                                 {
958                                                                         /* missing quote */
959                                                                         *result = 0;
960                                                                         return 0;
961                                                                 }
962                                                                 key++;
963                                                         }
964                                                         key++;
965                                                         for (unsigned j = 0; j < strlen(key); j++)
966                                                         {
967                                                                 if (key[j] == '"')
968                                                                 {
969                                                                         key[j] = '\0';
970                                                                 }
971                                                         }
972                                                         strlcpy(result,key,MAXBUF);
973                                                         return 1;
974                                                 }
975                                         }
976                                 }
977                         }
978                         if (!strcmp(c_tag,tag))
979                         {
980                                 /* correct tag, but wrong index */
981                                 idx++;
982                         }
983                         c_tag[0] = '\0';
984                         buffer[0] = '\0';
985                         ptr = 0;
986                         tptr = 0;
987                 }
988                 if (c != '>')
989                 {
990                         if ((in_token) && (c != '\n') && (c != '\r'))
991                         {
992                                 buffer[ptr++] = c;
993                                 buffer[ptr] = '\0';
994                         }
995                 }
996         }
997         *result = 0; // value or its tag not found at all
998         return 0;
999 }
1000
1001
1002
1003 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1004 {
1005         ReadConf(config, tag, var, index, result);
1006         return 0;
1007 }
1008
1009
1010
1011 // This will bind a socket to a port. It works for UDP/TCP
1012 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1013 {
1014         memset((char *)&server,0,sizeof(server));
1015         struct in_addr addy;
1016         inet_aton(addr,&addy);
1017         server.sin_family = AF_INET;
1018         if (!strcmp(addr,""))
1019         {
1020                 server.sin_addr.s_addr = htonl(INADDR_ANY);
1021         }
1022         else
1023         {
1024                 server.sin_addr = addy;
1025         }
1026         server.sin_port = htons(port);
1027         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1028         {
1029                 return(ERROR);
1030         }
1031         else
1032         {
1033                 listen(sockfd, Config->MaxConn);
1034                 return(TRUE);
1035         }
1036 }
1037
1038
1039 // Open a TCP Socket
1040 int OpenTCPSocket (void)
1041 {
1042         int sockfd;
1043         int on = 1;
1044         struct linger linger = { 0 };
1045   
1046         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1047                 return (ERROR);
1048         else
1049         {
1050                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1051                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1052                 linger.l_onoff = 1;
1053                 linger.l_linger = 1;
1054                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1055                 return (sockfd);
1056         }
1057 }
1058
1059 int BindPorts()
1060 {
1061         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1062         sockaddr_in client,server;
1063         int clientportcount = 0;
1064         int BoundPortCount = 0;
1065         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1066         {
1067                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1068                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1069                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1070                 if (strcmp(Type,"servers"))
1071                 {
1072                         // modules handle server bind types now,
1073                         // its not a typo in the strcmp.
1074                         Config->ports[clientportcount] = atoi(configToken);
1075                         strlcpy(Config->addrs[clientportcount],Addr,256);
1076                         clientportcount++;
1077                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1078                 }
1079         }
1080         int PortCount = clientportcount;
1081
1082         for (int count = 0; count < PortCount; count++)
1083         {
1084                 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1085                 {
1086                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1087                         return(ERROR);
1088                 }
1089                 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1090                 {
1091                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1092                 }
1093                 else    /* well we at least bound to one socket so we'll continue */
1094                 {
1095                         BoundPortCount++;
1096                 }
1097         }
1098
1099         /* if we didn't bind to anything then abort */
1100         if (!BoundPortCount)
1101         {
1102                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1103                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1104                 return (ERROR);
1105         }
1106
1107         return BoundPortCount;
1108 }
1109