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