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