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