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