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