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