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