]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
3ffa248a15fe2cabedff5d80474b0779fcfb5835
[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 "message.h"
29 #include "inspircd.h"
30 #include "inspircd_io.h"
31 #include "inspstring.h"
32 #include "helperfuncs.h"
33 #include "userprocess.h"
34 #include "xline.h"
35
36 extern ServerConfig *Config;
37 extern InspIRCd* ServerInstance;
38 extern int openSockfd[MAX_DESCRIPTORS];
39 extern time_t TIME;
40
41 extern int MODCOUNT;
42 extern std::vector<Module*> modules;
43 extern std::vector<ircd_module*> factory;
44
45 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
46
47 ServerConfig::ServerConfig()
48 {
49         this->ClearStack();
50         *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
51         *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
52         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
53         *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
54         log_file = NULL;
55         OperSpyWhois = nofork = HideBans = HideSplits = unlimitcore = false;
56         AllowHalfop = true;
57         dns_timeout = DieDelay = 5;
58         MaxTargets = 20;
59         NetBufferSize = 10240;
60         SoftLimit = MAXCLIENTS;
61         MaxConn = SOMAXCONN;
62         MaxWhoResults = 100;
63         debugging = 0;
64         LogLevel = DEFAULT;
65         maxbans.clear();
66 }
67
68 void ServerConfig::ClearStack()
69 {
70         include_stack.clear();
71 }
72
73 Module* ServerConfig::GetIOHook(int port)
74 {
75         std::map<int,Module*>::iterator x = IOHookModule.find(port);
76         return (x != IOHookModule.end() ? x->second : NULL);
77 }
78
79 bool ServerConfig::AddIOHook(int port, Module* iomod)
80 {
81         if (!GetIOHook(port))
82         {
83                 IOHookModule[port] = iomod;
84                 return true;
85         }
86         else
87         {
88                 ModuleException err("Port already hooked by another module");
89                 throw(err);
90                 return false;
91         }
92 }
93
94 bool ServerConfig::DelIOHook(int port)
95 {
96         std::map<int,Module*>::iterator x = IOHookModule.find(port);
97         if (x != IOHookModule.end())
98         {
99                 IOHookModule.erase(x);
100                 return true;
101         }
102         return false;
103 }
104
105 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
106 {
107         int count = ConfValueEnum(tag,&Config->config_f);
108         if (count > 1)
109         {
110                 if (bail)
111                 {
112                         printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
113                         Exit(0);
114                 }
115                 else
116                 {
117                         if (user)
118                         {
119                                 WriteServ(user->fd,"There were errors in your configuration:");
120                                 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
121                         }
122                         else
123                         {
124                                 WriteOpers("There were errors in the configuration file:");
125                                 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
126                         }
127                 }
128                 return false;
129         }
130         if (count < 1)
131         {
132                 if (bail)
133                 {
134                         printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
135                         Exit(0);
136                 }
137                 else
138                 {
139                         if (user)
140                         {
141                                 WriteServ(user->fd,"There were errors in your configuration:");
142                                 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
143                         }
144                         else
145                         {
146                                 WriteOpers("There were errors in the configuration file:");
147                                 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
148                         }
149                 }
150                 return false;
151         }
152         return true;
153 }
154
155 bool NoValidation(const char* tag, const char* value, void* data)
156 {
157         log(DEBUG,"No validation for <%s:%s>",tag,value);
158         return true;
159 }
160
161 bool ValidateTempDir(const char* tag, const char* value, void* data)
162 {
163         char* x = (char*)data;
164         if (!*x)
165                 strlcpy(x,"/tmp",1024);
166         return true;
167 }
168  
169 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
170 {
171         int* x = (int*)data;
172         if ((*x < 0) || (*x > 31))
173         {
174                 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
175                 *x = 20;
176         }
177         return true;
178 }
179
180 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
181 {
182         int* x = (int*)data;    
183         if ((*x < 1) || (*x > MAXCLIENTS))
184         {
185                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
186                 *x = MAXCLIENTS;
187         }
188         return true;
189 }
190
191 bool ValidateMaxConn(const char* tag, const char* value, void* data)
192 {
193         int* x = (int*)data;    
194         if (*x > SOMAXCONN)
195                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
196         if (!*x)
197                 *x = SOMAXCONN;
198         return true;
199 }
200
201 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
202 {
203         int* x = (int*)data;
204         if (!*x)
205                 *x = 5;
206         return true;
207 }
208
209 bool ValidateDnsServer(const char* tag, const char* value, void* data)
210 {
211         char* x = (char*)data;
212         if (!*x)
213         {
214                 // attempt to look up their nameserver from /etc/resolv.conf
215                 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
216                 ifstream resolv("/etc/resolv.conf");
217                 std::string nameserver;
218                 bool found_server = false;
219
220                 if (resolv.is_open())
221                 {
222                         while (resolv >> nameserver)
223                         {
224                                 if ((nameserver == "nameserver") && (!found_server))
225                                 {
226                                         resolv >> nameserver;
227                                         strlcpy(x,nameserver.c_str(),MAXBUF);
228                                         found_server = true;
229                                         log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
230                                 }
231                         }
232
233                         if (!found_server)
234                         {
235                                 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
236                                 strlcpy(x,"127.0.0.1",MAXBUF);
237                         }
238                 }
239                 else
240                 {
241                         log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
242                         strlcpy(x,"127.0.0.1",MAXBUF);
243                 }
244         }
245         return true;
246 }
247
248 bool ValidateModPath(const char* tag, const char* value, void* data)
249 {
250         char* x = (char*)data;  
251         if (!*x)
252                 strlcpy(x,MOD_PATH,MAXBUF);
253         return true;
254 }
255
256
257 bool ValidateServerName(const char* tag, const char* value, void* data)
258 {
259         char* x = (char*)data;
260         if (!strchr(x,'.'))
261         {
262                 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
263                 charlcat(x,'.',MAXBUF);
264         }
265         //strlower(x);
266         return true;
267 }
268
269 bool ValidateNetworkName(const char* tag, const char* value, void* data)
270 {
271         char* x = (char*)data;
272
273         log(DEFAULT,"<server:network> '%s'",x);
274
275         return true;
276 }
277
278 bool ValidateServerDesc(const char* tag, const char* value, void* data)
279 {
280         char* x = (char*)data;
281
282         log(DEFAULT,"<server:description> '%s'",x);
283
284         return true;
285 }
286
287 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
288 {
289         if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
290         {
291                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
292                 Config->NetBufferSize = 10240;
293         }
294         return true;
295 }
296
297 bool ValidateMaxWho(const char* tag, const char* value, void* data)
298 {
299         if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
300         {
301                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
302                 Config->MaxWhoResults = 128;
303         }
304         return true;
305 }
306
307 bool ValidateLogLevel(const char* tag, const char* value, void* data)
308 {
309         const char* dbg = (const char*)data;
310         Config->LogLevel = DEFAULT;
311         if (!strcmp(dbg,"debug"))
312         {
313                 Config->LogLevel = DEBUG;
314                 Config->debugging = 1;
315         }
316         else if (!strcmp(dbg,"verbose"))
317                 Config->LogLevel = VERBOSE;
318         else if (!strcmp(dbg,"default"))
319                 Config->LogLevel = DEFAULT;
320         else if (!strcmp(dbg,"sparse"))
321                 Config->LogLevel = SPARSE;
322         else if (!strcmp(dbg,"none"))
323                 Config->LogLevel = NONE;
324         return true;
325 }
326
327 bool ValidateMotd(const char* tag, const char* value, void* data)
328 {
329         readfile(Config->MOTD,Config->motd);
330         return true;
331 }
332
333 bool ValidateRules(const char* tag, const char* value, void* data)
334 {
335         readfile(Config->RULES,Config->rules);
336         return true;
337 }
338
339 /* Callback called before processing the first <connect> tag
340  */
341 bool InitConnect(const char* tag)
342 {
343         log(DEFAULT,"Reading connect classes...");
344         Config->Classes.clear();
345         return true;
346 }
347
348 /* Callback called to process a single <connect> tag
349  */
350 bool DoConnect(const char* tag, char** entries, void** values, int* types)
351 {
352         ConnectClass c;
353         char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
354         char* deny = (char*)values[1];
355         char* password = (char*)values[2];
356         int* timeout = (int*)values[3];
357         int* pingfreq = (int*)values[4];
358         int* flood = (int*)values[5];
359         int* threshold = (int*)values[6];
360         int* sendq = (int*)values[7];
361         int* recvq = (int*)values[8];
362         int* localmax = (int*)values[9];
363         int* globalmax = (int*)values[10];
364
365         if (*allow)
366         {
367                 c.host = allow;
368                 c.type = CC_ALLOW;
369                 c.pass = password;
370                 c.registration_timeout = *timeout;
371                 c.pingtime = *pingfreq;
372                 c.flood = *flood;
373                 c.threshold = *threshold;
374                 c.sendqmax = *sendq;
375                 c.recvqmax = *recvq;
376                 c.maxlocal = *localmax;
377                 c.maxglobal = *globalmax;
378
379
380                 if (c.maxlocal == 0)
381                         c.maxlocal = 3;
382                 if (c.maxglobal == 0)
383                         c.maxglobal = 3;
384                 if (c.threshold == 0)
385                 {
386                         c.threshold = 1;
387                         c.flood = 999;
388                         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());
389                 }
390                 if (c.sendqmax == 0)
391                         c.sendqmax = 262114;
392                 if (c.recvqmax == 0)
393                         c.recvqmax = 4096;
394                 if (c.registration_timeout == 0)
395                         c.registration_timeout = 90;
396                 if (c.pingtime == 0)
397                         c.pingtime = 120;
398                 Config->Classes.push_back(c);
399         }
400         else
401         {
402                 c.host = deny;
403                 c.type = CC_DENY;
404                 Config->Classes.push_back(c);
405                 log(DEBUG,"Read connect class type DENY, host=%s",deny);
406         }
407
408         return true;
409 }
410
411 /* Callback called when there are no more <connect> tags
412  */
413 bool DoneConnect(const char* tag)
414 {
415         log(DEBUG,"DoneConnect called for tag: %s",tag);
416         return true;
417 }
418
419 /* Callback called before processing the first <uline> tag
420  */
421 bool InitULine(const char* tag)
422 {
423         Config->ulines.clear();
424         return true;
425 }
426
427 /* Callback called to process a single <uline> tag
428  */
429 bool DoULine(const char* tag, char** entries, void** values, int* types)
430 {
431         char* server = (char*)values[0];
432         log(DEBUG,"Read ULINE '%s'",server);
433         Config->ulines.push_back(server);
434         return true;
435 }
436
437 /* Callback called when there are no more <uline> tags
438  */
439 bool DoneULine(const char* tag)
440 {
441         return true;
442 }
443
444 /* Callback called before processing the first <module> tag
445  */
446 bool InitModule(const char* tag)
447 {
448         old_module_names.clear();
449         new_module_names.clear();
450         added_modules.clear();
451         removed_modules.clear();
452         for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
453         {
454                 old_module_names.push_back(*t);
455         }
456         return true;
457 }
458
459 /* Callback called to process a single <module> tag
460  */
461 bool DoModule(const char* tag, char** entries, void** values, int* types)
462 {
463         char* modname = (char*)values[0];
464         new_module_names.push_back(modname);
465         return true;
466 }
467
468 /* Callback called when there are no more <module> tags
469  */
470 bool DoneModule(const char* tag)
471 {
472         // now create a list of new modules that are due to be loaded
473         // and a seperate list of modules which are due to be unloaded
474         for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
475         {
476                 bool added = true;
477
478                 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
479                 {
480                         if (*old == *_new)
481                                 added = false;
482                 }
483
484                 if (added)
485                         added_modules.push_back(*_new);
486         }
487
488         for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
489         {
490                 bool removed = true;
491                 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
492                 {
493                         if (*newm == *oldm)
494                                 removed = false;
495                 }
496
497                 if (removed)
498                         removed_modules.push_back(*oldm);
499         }
500         return true;
501 }
502
503 /* Callback called before processing the first <banlist> tag
504  */
505 bool InitMaxBans(const char* tag)
506 {
507         Config->maxbans.clear();
508         return true;
509 }
510
511 /* Callback called to process a single <banlist> tag
512  */
513 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
514 {
515         char* channel = (char*)values[0];
516         int* limit = (int*)values[1];
517         Config->maxbans[channel] = *limit;
518         return true;
519 }
520
521 /* Callback called when there are no more <banlist> tags.
522  */
523 bool DoneMaxBans(const char* tag)
524 {
525         return true;
526 }
527
528 void ServerConfig::Read(bool bail, userrec* user)
529 {
530         char debug[MAXBUF];             /* Temporary buffer for debugging value */
531         char dataline[1024];            /* Temporary buffer for error output */
532         char* convert;                  /* Temporary buffer used for reading singular values into */
533         char* data[12];                 /* Temporary buffers for reading multiple occurance tags into */
534         void* ptr[12];                  /* Temporary pointers for passing to callbacks */
535         int r_i[12];                    /* Temporary array for casting */
536         int rem = 0, add = 0;           /* Number of modules added, number of modules removed */
537         std::stringstream errstr;       /* String stream containing the error output */
538
539         /* These tags MUST occur and must ONLY occur once in the config file */
540         static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
541
542         /* These tags can occur ONCE or not at all */
543         static InitialConfig Values[] = {
544                 {"options",             "softlimit",            &this->SoftLimit,               DT_INTEGER, ValidateSoftLimit},
545                 {"options",             "somaxconn",            &this->MaxConn,                 DT_INTEGER, ValidateMaxConn},
546                 {"server",              "name",                         &this->ServerName,              DT_CHARPTR, ValidateServerName},
547                 {"server",              "description",          &this->ServerDesc,              DT_CHARPTR, ValidateServerDesc},
548                 {"server",              "network",                      &this->Network,                 DT_CHARPTR, ValidateNetworkName},
549                 {"admin",               "name",                         &this->AdminName,               DT_CHARPTR, NoValidation},
550                 {"admin",               "email",                        &this->AdminEmail,              DT_CHARPTR, NoValidation},
551                 {"admin",               "nick",                         &this->AdminNick,               DT_CHARPTR, NoValidation},
552                 {"files",               "motd",                         &this->motd,                    DT_CHARPTR, ValidateMotd},
553                 {"files",               "rules",                        &this->rules,                   DT_CHARPTR, ValidateRules},
554                 {"power",               "diepass",                      &this->diepass,                 DT_CHARPTR, NoValidation},      
555                 {"power",               "pauseval",                     &this->DieDelay,                DT_INTEGER, NoValidation},
556                 {"power",               "restartpass",          &this->restartpass,             DT_CHARPTR, NoValidation},
557                 {"options",             "prefixquit",           &this->PrefixQuit,              DT_CHARPTR, NoValidation},
558                 {"die",                 "value",                        &this->DieValue,                DT_CHARPTR, NoValidation},
559                 {"options",             "loglevel",                     &debug,                                 DT_CHARPTR, ValidateLogLevel},
560                 {"options",             "netbuffersize",        &this->NetBufferSize,   DT_INTEGER, ValidateNetBufferSize},
561                 {"options",             "maxwho",                       &this->MaxWhoResults,   DT_INTEGER, ValidateMaxWho},
562                 {"options",             "allowhalfop",          &this->AllowHalfop,             DT_BOOLEAN, NoValidation},
563                 {"dns",                 "server",                       &this->DNSServer,               DT_CHARPTR, ValidateDnsServer},
564                 {"dns",                 "timeout",                      &this->dns_timeout,             DT_INTEGER, ValidateDnsTimeout},
565                 {"options",             "moduledir",            &this->ModPath,                 DT_CHARPTR, ValidateModPath},
566                 {"disabled",    "commands",             &this->DisabledCommands,DT_CHARPTR, NoValidation},
567                 {"options",             "operonlystats",        &this->OperOnlyStats,   DT_CHARPTR, NoValidation},
568                 {"options",             "customversion",        &this->CustomVersion,   DT_CHARPTR, NoValidation},
569                 {"options",             "hidesplits",           &this->HideSplits,              DT_BOOLEAN, NoValidation},
570                 {"options",             "hidebans",                     &this->HideBans,                DT_BOOLEAN, NoValidation},
571                 {"options",             "hidewhois",            &this->HideWhoisServer, DT_CHARPTR, NoValidation},
572                 {"options",             "operspywhois",         &this->OperSpyWhois,    DT_BOOLEAN, NoValidation},
573                 {"options",             "tempdir",                      &this->TempDir,                 DT_CHARPTR, ValidateTempDir},
574                 {"pid",                 "file",                         &this->PID,                             DT_CHARPTR, NoValidation},
575                 {NULL}
576         };
577
578         /* These tags can occur multiple times, and therefore they have special code to read them
579          * which is different to the code for reading the singular tags listed above.
580          */
581         static MultiConfig MultiValues[] = {
582
583                 {"connect",
584                                 {"allow",       "deny",         "password",     "timeout",      "pingfreq",     "flood",
585                                 "threshold",    "sendq",        "recvq",        "localmax",     "globalmax",    NULL},
586                                 {DT_CHARPTR,    DT_CHARPTR,     DT_CHARPTR,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
587                                  DT_INTEGER,    DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER},
588                                 InitConnect, DoConnect, DoneConnect},
589
590                 {"uline",
591                                 {"server",      NULL},
592                                 {DT_CHARPTR},
593                                 InitULine,DoULine,DoneULine},
594
595                 {"banlist",
596                                 {"chan",        "limit",        NULL},
597                                 {DT_CHARPTR,    DT_INTEGER},
598                                 InitMaxBans, DoMaxBans, DoneMaxBans},
599
600                 {"module",
601                                 {"name",        NULL},
602                                 {DT_CHARPTR},
603                                 InitModule, DoModule, DoneModule},
604
605                 {"badip",
606                                 {"reason",      "ipmask",       NULL},
607                                 {DT_CHARPTR,    DT_CHARPTR},
608                                 InitXLine, DoZLine, DoneXLine},
609
610                 {"badnick",
611                                 {"reason",      "nick",         NULL},
612                                 {DT_CHARPTR,    DT_CHARPTR},
613                                 InitXLine, DoQLine, DoneXLine},
614
615                 {"badhost",
616                                 {"reason",      "host",         NULL},
617                                 {DT_CHARPTR,    DT_CHARPTR},
618                                 InitXLine, DoKLine, DoneXLine},
619
620                 {"exception",
621                                 {"reason",      "host",         NULL},
622                                 {DT_CHARPTR,    DT_CHARPTR},
623                                 InitXLine, DoELine, DoneXLine},
624
625                 {"type",
626                                 {"name",        "classes",      NULL},
627                                 {DT_CHARPTR,    DT_CHARPTR},
628                                 InitTypes, DoType, DoneClassesAndTypes},
629
630                 {"class",
631                                 {"name",        "commands",     NULL},
632                                 {DT_CHARPTR,    DT_CHARPTR},
633                                 InitClasses, DoClass, DoneClassesAndTypes},
634
635                 {NULL}
636         };
637
638         include_stack.clear();
639
640         /* Initially, load the config into memory, bail if there are errors
641          */
642         if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
643         {
644                 errstr.seekg(0);
645                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
646
647                 if (bail)
648                 {
649                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
650                         Exit(0);
651                 }
652                 else
653                 {
654                         if (user)
655                         {
656                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
657                                 while (!errstr.eof())
658                                 {
659                                         errstr.getline(dataline,1024);
660                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
661                                 }
662                         }
663                         else
664                         {
665                                 WriteOpers("There were errors in the configuration file:");
666                                 while (!errstr.eof())
667                                 {
668                                         errstr.getline(dataline,1024);
669                                         WriteOpers(dataline);
670                                 }
671                         }
672
673                         return;
674                 }
675         }
676
677         /* Check we dont have more than one of singular tags, or any of them missing
678          */
679         for (int Index = 0; Once[Index]; Index++)
680                 if (!CheckOnce(Once[Index],bail,user))
681                         return;
682
683         /* Read the values of all the tags which occur once or not at all, and call their callbacks.
684          */
685         for (int Index = 0; Values[Index].tag; Index++)
686         {
687                 int* val_i = (int*) Values[Index].val;
688                 char* val_c = (char*) Values[Index].val;
689
690                 switch (Values[Index].datatype)
691                 {
692                         case DT_CHARPTR:
693                                 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
694                         break;
695
696                         case DT_INTEGER:
697                                 convert = new char[MAXBUF];
698                                 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
699                                 *val_i = atoi(convert);
700                                 delete[] convert;
701                         break;
702
703                         case DT_BOOLEAN:
704                                 convert = new char[MAXBUF];
705                                 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
706                                 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
707                                 delete[] convert;
708                         break;
709
710                         case DT_NOTHING:
711                         break;
712                 }
713
714                 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
715         }
716
717         /* Claim memory for use when reading multiple tags
718          */
719         for (int n = 0; n < 12; n++)
720                 data[n] = new char[MAXBUF];
721
722         /* Read the multiple-tag items (class tags, connect tags, etc)
723          * and call the callbacks associated with them. We have three
724          * callbacks for these, a 'start', 'item' and 'end' callback.
725          */
726         for (int Index = 0; MultiValues[Index].tag; Index++)
727         {
728                 MultiValues[Index].init_function(MultiValues[Index].tag);
729
730                 int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f);
731
732                 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
733                 {
734                         for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
735                         {
736                                 ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f);
737
738                                 switch (MultiValues[Index].datatype[valuenum])
739                                 {
740                                         case DT_CHARPTR:
741                                                 ptr[valuenum] = data[valuenum];
742                                         break;
743                                         case DT_INTEGER:
744                                                 r_i[valuenum] = atoi(data[valuenum]);
745                                                 ptr[valuenum] = &r_i[valuenum];
746                                         break;
747                                         case DT_BOOLEAN:
748                                                 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
749                                                 ptr[valuenum] = &r_i[valuenum];
750                                         break;
751                                         default:
752                                         break;
753                                 }
754                         }
755                         MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
756                 }
757
758                 MultiValues[Index].finish_function(MultiValues[Index].tag);
759         }
760
761         /* Free any memory we claimed
762          */
763         for (int n = 0; n < 12; n++)
764                 delete[] data[n];
765
766         // write once here, to try it out and make sure its ok
767         WritePID(Config->PID);
768
769         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
770
771         /* If we're rehashing, let's load any new modules, and unload old ones
772          */
773         if (!bail)
774         {
775                 ServerInstance->stats->BoundPortCount = BindPorts(false);
776
777                 if (!removed_modules.empty())
778                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
779                         {
780                                 if (ServerInstance->UnloadModule(removing->c_str()))
781                                 {
782                                         WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
783
784                                         if (user)
785                                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
786
787                                         rem++;
788                                 }
789                                 else
790                                 {
791                                         if (user)
792                                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
793                                 }
794                         }
795
796                 if (!added_modules.empty())
797                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
798                 {
799                         if (ServerInstance->LoadModule(adding->c_str()))
800                         {
801                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
802
803                                 if (user)
804                                         WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
805
806                                 add++;
807                         }
808                         else
809                         {
810                                 if (user)
811                                         WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
812                         }
813                 }
814
815                 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
816         }
817 }
818
819 void Exit(int status)
820 {
821         if (Config->log_file)
822                 fclose(Config->log_file);
823         send_error("Server shutdown.");
824         exit (status);
825 }
826
827 void Killed(int status)
828 {
829         if (Config->log_file)
830                 fclose(Config->log_file);
831         send_error("Server terminated.");
832         exit(status);
833 }
834
835 char* CleanFilename(char* name)
836 {
837         char* p = name + strlen(name);
838         while ((p != name) && (*p != '/')) p--;
839         return (p != name ? ++p : p);
840 }
841
842
843 void Rehash(int status)
844 {
845         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
846         fclose(Config->log_file);
847         OpenLog(NULL,0);
848         Config->Read(false,NULL);
849         FOREACH_MOD(I_OnRehash,OnRehash(""));
850 }
851
852
853
854 void Start()
855 {
856         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
857         printf("(C) ChatSpike Development team.\033[0m\n\n");
858         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
859         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
860         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
861 }
862
863 void WritePID(const std::string &filename)
864 {
865         ofstream outfile(filename.c_str());
866         if (outfile.is_open())
867         {
868                 outfile << getpid();
869                 outfile.close();
870         }
871         else
872         {
873                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
874                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
875                 Exit(0);
876         }
877 }
878
879 void SetSignals()
880 {
881         signal (SIGALRM, SIG_IGN);
882         signal (SIGHUP, Rehash);
883         signal (SIGPIPE, SIG_IGN);
884         signal (SIGTERM, Exit);
885         signal (SIGSEGV, Error);
886 }
887
888
889 bool DaemonSeed()
890 {
891         int childpid;
892         if ((childpid = fork ()) < 0)
893                 return (ERROR);
894         else if (childpid > 0)
895         {
896                 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
897                 sleep(6);
898                 exit (0);
899         }
900         setsid ();
901         umask (007);
902         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
903
904         if (Config->unlimitcore)
905         {
906                 rlimit rl;
907                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
908                 {
909                         log(DEFAULT,"Failed to getrlimit()!");
910                         return false;
911                 }
912                 else
913                 {
914                         rl.rlim_cur = rl.rlim_max;
915                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
916                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
917                 }
918         }
919   
920         return true;
921 }
922
923
924 /* Make Sure Modules Are Avaliable!
925  * (BugFix By Craig.. See? I do work! :p)
926  * Modified by brain, requires const char*
927  * to work with other API functions
928  */
929
930 bool FileExists (const char* file)
931 {
932         FILE *input;
933         if ((input = fopen (file, "r")) == NULL)
934         {
935                 return(false);
936         }
937         else
938         {
939                 fclose (input);
940                 return(true);
941         }
942 }
943
944 /* ConfProcess does the following things to a config line in the following order:
945  *
946  * Processes the line for syntax errors as shown below
947  *  (1) Line void of quotes or equals (a malformed, illegal tag format)
948  *  (2) Odd number of quotes on the line indicating a missing quote
949  *  (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
950  *  (4) Spaces between the opening bracket (<) and the keyword
951  *  (5) Spaces between a keyword and an equals sign
952  *  (6) Spaces between an equals sign and a quote
953  * Removes trailing spaces
954  * Removes leading spaces
955  * Converts tabs to spaces
956  * Turns multiple spaces that are outside of quotes into single spaces
957  */
958
959 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
960 {
961         long number_of_quotes = 0;
962         long number_of_equals = 0;
963         bool has_open_bracket = false;
964         bool in_quotes = false;
965         char* trailing;
966
967         error = false;
968         if (!buffer)
969         {
970                 return "";
971         }
972         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
973         for (char* d = buffer; *d; d++)
974                 if (*d == 9)
975                         *d = ' ';
976         while (*buffer == ' ') buffer++;
977         trailing = buffer + strlen(buffer) - 1;
978         while (*trailing == ' ') *trailing-- = '\0';
979
980         // empty lines are syntactically valid, as are comments
981         if (!(*buffer) || buffer[0] == '#')
982                 return "";
983
984         for (char* c = buffer; *c; c++)
985         {
986                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
987                 // search and replace later :)
988                 if ((!in_quotes) && (*c == ' '))
989                         *c = '\xA0';
990                 if ((*c == '<') && (!in_quotes))
991                 {
992                         has_open_bracket = true;
993                         if (!(*(buffer+1)))
994                         {
995                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
996                                 error = true;
997                                 return "";
998                         }
999                         else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
1000                         {
1001                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
1002                                 error = true;
1003                                 return "";
1004                         }
1005                 }
1006                 if (*c == '"')
1007                 {
1008                         number_of_quotes++;
1009                         in_quotes = (!in_quotes);
1010                 }
1011                 if ((*c == '=') && (!in_quotes))
1012                 {
1013                         number_of_equals++;
1014                         if (*(c+1) == 0)
1015                         {
1016                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
1017                                 error = true;
1018                                 return "";
1019                         }
1020                         else if (*(c+1) != '"')
1021                         {
1022                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1023                                 error = true;
1024                                 return "";
1025                         }
1026                         else if (c == buffer)
1027                         {
1028                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
1029                                 error = true;
1030                                 return "";
1031                         }
1032                         else if (*(c-1) == '\xA0')
1033                         {
1034                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1035                                 error = true;
1036                                 return "";
1037                         }
1038                 }
1039         }
1040         // no quotes, and no equals. something freaky.
1041         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
1042         {
1043                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
1044                 error = true;
1045                 return "";
1046         }
1047         // odd number of quotes. thats just wrong.
1048         if ((number_of_quotes % 2) != 0)
1049         {
1050                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
1051                 error = true;
1052                 return "";
1053         }
1054         if (number_of_equals < (number_of_quotes/2))
1055         {
1056                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
1057         }
1058         if (number_of_equals > (number_of_quotes/2))
1059         {
1060                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
1061         }
1062
1063         std::string parsedata = buffer;
1064         // turn multispace into single space
1065         while (parsedata.find("\xA0\xA0") != std::string::npos)
1066         {
1067                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
1068         }
1069
1070         // turn our hardspace back into softspace
1071         for (unsigned int d = 0; d < parsedata.length(); d++)
1072         {
1073                 if (parsedata[d] == '\xA0')
1074                         parsedata[d] = ' ';
1075         }
1076
1077         // and we're done, the line is fine!
1078         return parsedata;
1079 }
1080
1081 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
1082 {
1083         char c_read = 0;
1084         size_t n = 0;
1085         char* bufptr = buffer;
1086         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
1087         {
1088                 c_read = fgetc(file);
1089                 if ((c_read != '\n') && (c_read != '\r'))
1090                 {
1091                         *bufptr++ = c_read;
1092                         n++;
1093                 }
1094         }
1095         *bufptr = 0;
1096         return bufptr - buffer;
1097 }
1098
1099 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
1100 {
1101         target->str("");
1102         errorstream->str("");
1103         long linenumber = 1;
1104         // first, check that the file exists before we try to do anything with it
1105         if (!FileExists(filename))
1106         {
1107                 *errorstream << "File " << filename << " not found." << endl;
1108                 return false;
1109         }
1110         // Fix the chmod of the file to restrict it to the current user and group
1111         chmod(filename,0600);
1112         for (unsigned int t = 0; t < include_stack.size(); t++)
1113         {
1114                 if (std::string(filename) == include_stack[t])
1115                 {
1116                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
1117                         return false;
1118                 }
1119         }
1120         include_stack.push_back(filename);
1121         // now open it
1122         FILE* conf = fopen(filename,"r");
1123         char buffer[MAXBUF];
1124         if (conf)
1125         {
1126                 while (!feof(conf))
1127                 {
1128                         if (fgets_safe(buffer, MAXBUF, conf))
1129                         {
1130                                 if ((!feof(conf)) && (buffer) && (*buffer))
1131                                 {
1132                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
1133                                         {
1134                                                 if (!strncmp(buffer,"<include file=\"",15))
1135                                                 {
1136                                                         char* buf = buffer;
1137                                                         char confpath[10240],newconf[10240];
1138                                                         // include file directive
1139                                                         buf += 15;      // advance to filename
1140                                                         for (char* j = buf; *j; j++)
1141                                                         {
1142                                                                 if (*j == '\\')
1143                                                                         *j = '/';
1144                                                                 if (*j == '"')
1145                                                                 {
1146                                                                         *j = 0;
1147                                                                         break;
1148                                                                 }
1149                                                         }
1150                                                         log(DEBUG,"Opening included file '%s'",buf);
1151                                                         if (*buf != '/')
1152                                                         {
1153                                                                 strlcpy(confpath,CONFIG_FILE,10240);
1154                                                                 if (strstr(confpath,"/inspircd.conf"))
1155                                                                 {
1156                                                                         // leaves us with just the path
1157                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
1158                                                                 }
1159                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
1160                                                         }
1161                                                         else strlcpy(newconf,buf,10240);
1162                                                         std::stringstream merge(stringstream::in | stringstream::out);
1163                                                         // recursively call LoadConf and get the new data, use the same errorstream
1164                                                         if (LoadConf(newconf, &merge, errorstream))
1165                                                         {
1166                                                                 // append to the end of the file
1167                                                                 std::string newstuff = merge.str();
1168                                                                 *target << newstuff;
1169                                                         }
1170                                                         else
1171                                                         {
1172                                                                 // the error propogates up to its parent recursively
1173                                                                 // causing the config reader to bail at the top level.
1174                                                                 fclose(conf);
1175                                                                 return false;
1176                                                         }
1177                                                 }
1178                                                 else
1179                                                 {
1180                                                         bool error = false;
1181                                                         std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1182                                                         if (error)
1183                                                         {
1184                                                                 return false;
1185                                                         }
1186                                                         *target << data;
1187                                                 }
1188                                         }
1189                                         else linenumber++;
1190                                 }
1191                         }
1192                 }
1193                 fclose(conf);
1194         }
1195         target->seekg(0);
1196         return true;
1197 }
1198
1199 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1200
1201 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1202 {
1203         int ptr = 0;
1204         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1205         int in_token, in_quotes, tptr, idx = 0;
1206
1207         std::string x = config->str();
1208         const char* buf = x.c_str();
1209         char* bptr = (char*)buf;
1210         
1211         ptr = 0;
1212         in_token = 0;
1213         in_quotes = 0;
1214         lastc = '\0';
1215         while (*bptr)
1216         {
1217                 lastc = c;
1218                 c = *bptr++;
1219                 if ((c == '#') && (lastc == '\n'))
1220                 {
1221                         while ((c != '\n') && (*bptr))
1222                         {
1223                                 lastc = c;
1224                                 c = *bptr++;
1225                         }
1226                 }
1227                 if ((c == '<') && (!in_quotes))
1228                 {
1229                         tptr = 0;
1230                         in_token = 1;
1231                         do {
1232                                 c = *bptr++;
1233                                 if (c != ' ')
1234                                 {
1235                                         c_tag[tptr++] = c;
1236                                         c_tag[tptr] = '\0';
1237                                 }
1238                         } while (c != ' ');
1239                 }
1240                 if (c == '"')
1241                 {
1242                         in_quotes = (!in_quotes);
1243                 }
1244                 if ((c == '>') && (!in_quotes))
1245                 {
1246                         in_token = 0;
1247                         if (!strcmp(c_tag,tag))
1248                         {
1249                                 /* correct tag, but wrong index */
1250                                 idx++;
1251                         }
1252                         c_tag[0] = '\0';
1253                         buffer[0] = '\0';
1254                         ptr = 0;
1255                         tptr = 0;
1256                 }
1257                 if (c != '>')
1258                 {
1259                         if ((in_token) && (c != '\n') && (c != '\r'))
1260                         {
1261                                 buffer[ptr++] = c;
1262                                 buffer[ptr] = '\0';
1263                         }
1264                 }
1265         }
1266         return idx;
1267 }
1268
1269 /* Counts the number of values within a certain tag */
1270
1271 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1272 {
1273         int ptr = 0;
1274         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1275         int in_token, in_quotes, tptr, idx = 0;
1276         bool correct_tag = false;
1277         int num_items = 0;
1278         const char* buf = config->str().c_str();
1279         char* bptr = (char*)buf;
1280
1281         ptr = 0;
1282         in_token = 0;
1283         in_quotes = 0;
1284         lastc = 0;
1285
1286         while (*bptr)
1287         {
1288                 lastc = c;
1289                 c = *bptr++;
1290                 if ((c == '#') && (lastc == '\n'))
1291                 {
1292                         while ((c != '\n') && (*bptr))
1293                         {
1294                                 lastc = c;
1295                                 c = *bptr++;
1296                         }
1297                 }
1298                 if ((c == '<') && (!in_quotes))
1299                 {
1300                         tptr = 0;
1301                         in_token = 1;
1302                         do {
1303                                 c = *bptr++;
1304                                 if (c != ' ')
1305                                 {
1306                                         c_tag[tptr++] = c;
1307                                         c_tag[tptr] = '\0';
1308                                         
1309                                         if ((!strcmp(c_tag,tag)) && (idx == index))
1310                                         {
1311                                                 correct_tag = true;
1312                                         }
1313                                 }
1314                         } while (c != ' ');
1315                 }
1316                 if (c == '"')
1317                 {
1318                         in_quotes = (!in_quotes);
1319                 }
1320                 
1321                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1322                 {
1323                         num_items++;
1324                 }
1325                 if ((c == '>') && (!in_quotes))
1326                 {
1327                         in_token = 0;
1328                         if (correct_tag)
1329                                 correct_tag = false;
1330                         if (!strcmp(c_tag,tag))
1331                         {
1332                                 /* correct tag, but wrong index */
1333                                 idx++;
1334                         }
1335                         c_tag[0] = '\0';
1336                         buffer[0] = '\0';
1337                         ptr = 0;
1338                         tptr = 0;
1339                 }
1340                 if (c != '>')
1341                 {
1342                         if ((in_token) && (c != '\n') && (c != '\r'))
1343                         {
1344                                 buffer[ptr++] = c;
1345                                 buffer[ptr] = '\0';
1346                         }
1347                 }
1348         }
1349         return num_items+1;
1350 }
1351
1352
1353 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1354 {
1355         return EnumConf(config,tag);
1356 }
1357
1358
1359 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1360 {
1361         int ptr = 0;
1362         char buffer[65535], c_tag[MAXBUF], c, lastc, varname[MAXBUF];
1363         int in_token, in_quotes, tptr, idx = 0;
1364         char* key;
1365         char* bptr = (char*)config->str().c_str();
1366         
1367         ptr = 0;
1368         in_token = 0;
1369         in_quotes = 0;
1370         lastc = 0;
1371         c_tag[0] = 0;
1372         buffer[0] = 0;
1373         
1374         /*
1375          * Fun bug here, if was searching for whatever var was  *in the whole tag*,
1376          * so if you had the name of the var you were searching for in one of the values
1377          * it would try to use that part of a value as the varnme, usually giving a value
1378          * something like "anothervarname="
1379          */
1380         strlcpy(varname, var, MAXBUF);
1381         strlcat(varname, "=", MAXBUF);
1382
1383         while (*bptr)
1384         {
1385                 lastc = c;
1386                 c = *bptr++;
1387                 // FIX: Treat tabs as spaces
1388                 if (c == 9)
1389                         c = 32;
1390                 if ((c == '<') && (!in_quotes))
1391                 {
1392                         tptr = 0;
1393                         in_token = 1;
1394                         do {
1395                                 c = *bptr++;
1396                                 if (c != ' ')
1397                                 {
1398                                         c_tag[tptr++] = c;
1399                                         c_tag[tptr] = '\0';
1400                                 }
1401                         // FIX: Tab can follow a tagname as well as space.
1402                         } while ((c != ' ') && (c != 9));
1403                 }
1404                 if (c == '"')
1405                 {
1406                         in_quotes = (!in_quotes);
1407                 }
1408                 if ((c == '>') && (!in_quotes))
1409                 {
1410                         in_token = 0;
1411                         if (idx == index)
1412                         {
1413                                 if (!strcmp(c_tag,tag))
1414                                 {
1415                                         if ((buffer) && (c_tag) && (var))
1416                                         {
1417                                                 key = strstr(buffer,varname);
1418                                                 if (!key)
1419                                                 {
1420                                                         /* value not found in tag */
1421                                                         *result = 0;
1422                                                         return 0;
1423                                                 }
1424                                                 else
1425                                                 {
1426                                                         key+=strlen(var);
1427                                                         while (*key !='"')
1428                                                         {
1429                                                                 if (!*key)
1430                                                                 {
1431                                                                         /* missing quote */
1432                                                                         *result = 0;
1433                                                                         return 0;
1434                                                                 }
1435                                                                 key++;
1436                                                         }
1437                                                         key++;
1438                                                         for (char* j = key; *j; j++)
1439                                                         {
1440                                                                 if (*j == '"')
1441                                                                 {
1442                                                                         *j = 0;
1443                                                                         break;
1444                                                                 }
1445                                                         }
1446                                                         strlcpy(result,key,MAXBUF);
1447                                                         return 1;
1448                                                 }
1449                                         }
1450                                 }
1451                         }
1452                         if (!strcmp(c_tag,tag))
1453                         {
1454                                 /* correct tag, but wrong index */
1455                                 idx++;
1456                         }
1457                         c_tag[0] = '\0';
1458                         buffer[0] = '\0';
1459                         ptr = 0;
1460                         tptr = 0;
1461                 }
1462                 if (c != '>')
1463                 {
1464                         if ((in_token) && (c != '\n') && (c != '\r'))
1465                         {
1466                                 buffer[ptr++] = c;
1467                                 buffer[ptr] = '\0';
1468                         }
1469                 }
1470         }
1471         
1472         *result = 0; // value or its tag not found at all
1473         return 0;
1474 }
1475
1476
1477
1478 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1479 {
1480         ReadConf(config, tag, var, index, result);
1481         return 0;
1482 }
1483
1484 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1485 {
1486         char result[MAXBUF];
1487         ReadConf(config, tag, var, index, result);
1488         return atoi(result);
1489 }
1490
1491 /** This will bind a socket to a port. It works for UDP/TCP.
1492  * If a hostname is given to bind to, the function will first
1493  * attempt to resolve the hostname, then bind to the IP the 
1494  * hostname resolves to. This is a blocking lookup blocking for
1495  * a maximum of one second before it times out, using the DNS
1496  * server specified in the configuration file.
1497  */ 
1498 bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1499 {
1500         memset((char *)&server,0,sizeof(server));
1501         struct in_addr addy;
1502         bool resolved = false;
1503         char resolved_addr[128];
1504
1505         if (*addr == '*')
1506                 *addr = 0;
1507
1508         if (*addr && !inet_aton(addr,&addy))
1509         {
1510                 /* If they gave a hostname, bind to the IP it resolves to */
1511                 if (CleanAndResolve(resolved_addr, addr, true))
1512                 {
1513                         inet_aton(resolved_addr,&addy);
1514                         log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1515                         server.sin_addr = addy;
1516                         resolved = true;
1517                 }
1518                 else
1519                 {
1520                         log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1521                         return false;
1522                 }
1523         }
1524         server.sin_family = AF_INET;
1525         if (!resolved)
1526         {
1527                 if (!*addr)
1528                 {
1529                         server.sin_addr.s_addr = htonl(INADDR_ANY);
1530                 }
1531                 else
1532                 {
1533                         server.sin_addr = addy;
1534                 }
1535         }
1536         server.sin_port = htons(port);
1537         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1538         {
1539                 return false;
1540         }
1541         else
1542         {
1543                 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1544                 if (listen(sockfd, Config->MaxConn) == -1)
1545                 {
1546                         log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1547                         return false;
1548                 }
1549                 else
1550                 {
1551                         NonBlocking(sockfd);
1552                         return true;
1553                 }
1554         }
1555 }
1556
1557
1558 // Open a TCP Socket
1559 int OpenTCPSocket()
1560 {
1561         int sockfd;
1562         int on = 1;
1563         struct linger linger = { 0 };
1564   
1565         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1566         {
1567                 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1568                 return (ERROR);
1569         }
1570         else
1571         {
1572                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1573                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1574                 linger.l_onoff = 1;
1575                 linger.l_linger = 1;
1576                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1577                 return (sockfd);
1578         }
1579 }
1580
1581 bool HasPort(int port, char* addr)
1582 {
1583         for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1584         {
1585                 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1586                 {
1587                         return true;
1588                 }
1589         }
1590         return false;
1591 }
1592
1593 int BindPorts(bool bail)
1594 {
1595         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1596         sockaddr_in client,server;
1597         int clientportcount = 0;
1598         int BoundPortCount = 0;
1599
1600         if (!bail)
1601         {
1602                 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1603                 log(DEBUG,"Initial port count: %d",InitialPortCount);
1604
1605                 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1606                 {
1607                         Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1608                         Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1609                         Config->ConfValue("bind","type",count,Type,&Config->config_f);
1610                         if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1611                         {
1612                                 // modules handle server bind types now
1613                                 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1614                                 if (*Addr == '*')
1615                                         *Addr = 0;
1616
1617                                 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1618                                 clientportcount++;
1619                                 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1620                         }
1621                 }
1622                 int PortCount = clientportcount;
1623                 if (PortCount)
1624                 {
1625                         for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1626                         {
1627                                 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1628                                 {
1629                                         log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1630                                         return ERROR;
1631                                 }
1632                                 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1633                                 {
1634                                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1635                                 }
1636                                 else
1637                                 {
1638                                         /* Associate the new open port with a slot in the socket engine */
1639                                         ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1640                                         BoundPortCount++;
1641                                 }
1642                         }
1643                         return InitialPortCount + BoundPortCount;
1644                 }
1645                 else
1646                 {
1647                         log(DEBUG,"There is nothing new to bind!");
1648                 }
1649                 return InitialPortCount;
1650         }
1651
1652         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1653         {
1654                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1655                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1656                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1657
1658                 if ((!*Type) || (!strcmp(Type,"clients")))
1659                 {
1660                         // modules handle server bind types now
1661                         Config->ports[clientportcount] = atoi(configToken);
1662
1663                         // If the client put bind "*", this is an unrealism.
1664                         // We don't actually support this as documented, but
1665                         // i got fed up of people trying it, so now it converts
1666                         // it to an empty string meaning the same 'bind to all'.
1667                         if (*Addr == '*')
1668                                 *Addr = 0;
1669
1670                         strlcpy(Config->addrs[clientportcount],Addr,256);
1671                         clientportcount++;
1672                         log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1673                 }
1674         }
1675
1676         int PortCount = clientportcount;
1677
1678         for (int count = 0; count < PortCount; count++)
1679         {
1680                 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1681                 {
1682                         log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1683                         return ERROR;
1684                 }
1685
1686                 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1687                 {
1688                         log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1689                 }
1690                 else
1691                 {
1692                         /* well we at least bound to one socket so we'll continue */
1693                         BoundPortCount++;
1694                 }
1695         }
1696
1697         /* if we didn't bind to anything then abort */
1698         if (!BoundPortCount)
1699         {
1700                 log(DEFAULT,"No ports bound, bailing!");
1701                 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1702                 return ERROR;
1703         }
1704
1705         return BoundPortCount;
1706 }