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