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