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