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