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