]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Add some defaults to serverconfig, removing need to set them in validate methods...
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "configreader.h"
15 #include <sstream>
16 #include <fstream>
17 #include "inspircd.h"
18 #include "xline.h"
19 #include "exitcodes.h"
20
21 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
22
23 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
24 {
25         this->ClearStack();
26         *ServerName = *Network = *ServerDesc = *AdminName = '\0';
27         *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
28         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
29         *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
30         WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
31         log_file = NULL;
32         NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
33         CycleHosts = writelog = AllowHalfop = true;
34         dns_timeout = DieDelay = 5;
35         MaxTargets = 20;
36         NetBufferSize = 10240;
37         SoftLimit = MAXCLIENTS;
38         MaxConn = SOMAXCONN;
39         MaxWhoResults = 100;
40         debugging = 0;
41         LogLevel = DEFAULT;
42         maxbans.clear();
43 }
44
45 void ServerConfig::ClearStack()
46 {
47         include_stack.clear();
48 }
49
50 Module* ServerConfig::GetIOHook(int port)
51 {
52         std::map<int,Module*>::iterator x = IOHookModule.find(port);
53         return (x != IOHookModule.end() ? x->second : NULL);
54 }
55
56 Module* ServerConfig::GetIOHook(InspSocket* is)
57 {
58         std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
59         return (x != SocketIOHookModule.end() ? x->second : NULL);
60 }
61
62 bool ServerConfig::AddIOHook(int port, Module* iomod)
63 {
64         if (!GetIOHook(port))
65         {
66                 IOHookModule[port] = iomod;
67                 return true;
68         }
69         else
70         {
71                 throw ModuleException("Port already hooked by another module");
72                 return false;
73         }
74 }
75
76 bool ServerConfig::AddIOHook(Module* iomod, InspSocket* is)
77 {
78         if (!GetIOHook(is))
79         {
80                 ServerInstance->Log(DEBUG,"Hooked inspsocket %08x", is);
81                 SocketIOHookModule[is] = iomod;
82                 is->IsIOHooked = true;
83                 return true;
84         }
85         else
86         {
87                 throw ModuleException("InspSocket derived class already hooked by another module");
88                 return false;
89         }
90 }
91
92 bool ServerConfig::DelIOHook(int port)
93 {
94         std::map<int,Module*>::iterator x = IOHookModule.find(port);
95         if (x != IOHookModule.end())
96         {
97                 IOHookModule.erase(x);
98                 return true;
99         }
100         return false;
101 }
102
103 bool ServerConfig::DelIOHook(InspSocket* is)
104 {
105         std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
106         if (x != SocketIOHookModule.end())
107         {
108                 SocketIOHookModule.erase(x);
109                 return true;
110         }
111         return false;
112 }
113
114 void ServerConfig::Update005()
115 {
116         std::stringstream out(data005);
117         std::string token;
118         std::string line5;
119         int token_counter = 0;
120         isupport.clear();
121         while (out >> token)
122         {
123                 line5 = line5 + token + " ";
124                 token_counter++;
125                 if (token_counter >= 13)
126                 {
127                         char buf[MAXBUF];
128                         snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
129                         isupport.push_back(buf);
130                         line5 = "";
131                         token_counter = 0;
132                 }
133         }
134         char buf[MAXBUF];
135         snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
136         isupport.push_back(buf);
137 }
138
139 void ServerConfig::Send005(userrec* user)
140 {
141         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
142                 user->WriteServ("005 %s %s", user->nick, line->c_str());
143 }
144
145 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
146 {
147         int count = ConfValueEnum(this->config_data, tag);
148         
149         if (count > 1)
150         {
151                 if (bail)
152                 {
153                         printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
154                         InspIRCd::Exit(EXIT_STATUS_CONFIG);
155                 }
156                 else
157                 {
158                         if (user)
159                         {
160                                 user->WriteServ("There were errors in your configuration:");
161                                 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
162                         }
163                         else
164                         {
165                                 ServerInstance->WriteOpers("There were errors in the configuration file:");
166                                 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
167                         }
168                 }
169                 return false;
170         }
171         if (count < 1)
172         {
173                 if (bail)
174                 {
175                         printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
176                         InspIRCd::Exit(EXIT_STATUS_CONFIG);
177                 }
178                 else
179                 {
180                         if (user)
181                         {
182                                 user->WriteServ("There were errors in your configuration:");
183                                 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
184                         }
185                         else
186                         {
187                                 ServerInstance->WriteOpers("There were errors in the configuration file:");
188                                 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
189                         }
190                 }
191                 return false;
192         }
193         return true;
194 }
195
196 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
197 {
198         conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
199         return true;
200 }
201
202 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
203 {
204         if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
205         {
206                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
207                 data.Set(20);
208         }
209         return true;
210 }
211
212 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
213 {
214         if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
215         {
216                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
217                 data.Set(MAXCLIENTS);
218         }
219         return true;
220 }
221
222 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
223 {
224         if (data.GetInteger() > SOMAXCONN)
225                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
226         return true;
227 }
228
229 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
230 {
231         std::stringstream dcmds(data);
232         std::string thiscmd;
233
234         /* Enable everything first */
235         for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
236                 x->second->Disable(false);
237
238         /* Now disable all the ones which the user wants disabled */
239         while (dcmds >> thiscmd)
240         {
241                 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
242                 if (cm != ServerInstance->Parser->cmdlist.end())
243                 {
244                         ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
245                         cm->second->Disable(true);
246                 }
247         }
248         return true;
249 }
250
251 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
252 {
253         if (!*(data.GetString()))
254         {
255                 // attempt to look up their nameserver from /etc/resolv.conf
256                 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
257                 ifstream resolv("/etc/resolv.conf");
258                 std::string nameserver;
259                 bool found_server = false;
260
261                 if (resolv.is_open())
262                 {
263                         while (resolv >> nameserver)
264                         {
265                                 if ((nameserver == "nameserver") && (!found_server))
266                                 {
267                                         resolv >> nameserver;
268                                         data.Set(nameserver.c_str());
269                                         found_server = true;
270                                         conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
271                                 }
272                         }
273
274                         if (!found_server)
275                         {
276                                 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
277                                 data.Set("127.0.0.1");
278                         }
279                 }
280                 else
281                 {
282                         conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
283                         data.Set("127.0.0.1");
284                 }
285         }
286         return true;
287 }
288
289 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
290 {
291         if (!*(data.GetString()))
292                 data.Set(MOD_PATH);
293         return true;
294 }
295
296
297 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
298 {
299         if (!strchr(data.GetString(),'.'))
300         {
301                 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
302                 std::string moo = std::string(data.GetString()).append(".");
303                 data.Set(moo.c_str());
304         }
305         return true;
306 }
307
308 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
309 {
310         if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
311         {
312                 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
313                 data.Set(10240);
314         }
315         return true;
316 }
317
318 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
319 {
320         if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1))
321         {
322                 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
323                 data.Set(128);
324         }
325         return true;
326 }
327
328 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
329 {
330         std::string dbg = data.GetString();
331         conf->LogLevel = DEFAULT;
332
333         if (dbg == "debug")
334                 conf->LogLevel = DEBUG;
335         else if (dbg  == "verbose")
336                 conf->LogLevel = VERBOSE;
337         else if (dbg == "default")
338                 conf->LogLevel = DEFAULT;
339         else if (dbg == "sparse")
340                 conf->LogLevel = SPARSE;
341         else if (dbg == "none")
342                 conf->LogLevel = NONE;
343
344         conf->debugging = (conf->LogLevel == DEBUG);
345
346         return true;
347 }
348
349 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
350 {
351         conf->ReadFile(conf->MOTD, data.GetString());
352         return true;
353 }
354
355 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
356 {
357         conf->ReadFile(conf->RULES, data.GetString());
358         return true;
359 }
360
361 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
362 {
363         conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
364
365         if (conf->WhoWasGroupSize < 0)
366                 conf->WhoWasGroupSize = 0;
367
368         if (conf->WhoWasMaxGroups < 0)
369                 conf->WhoWasMaxGroups = 0;
370
371         if (conf->WhoWasMaxKeep < 3600)
372         {
373                 conf->WhoWasMaxKeep = 3600;
374                 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
375         }
376         conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
377         irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
378         return true;
379 }
380
381 /* Callback called before processing the first <connect> tag
382  */
383 bool InitConnect(ServerConfig* conf, const char* tag)
384 {
385         conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
386         conf->Classes.clear();
387         return true;
388 }
389
390 /* Callback called to process a single <connect> tag
391  */
392 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
393 {
394         ConnectClass c;
395         const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
396         const char* deny = values[1].GetString();
397         const char* password = values[2].GetString();
398         int timeout = values[3].GetInteger();
399         int pingfreq = values[4].GetInteger();
400         int flood = values[5].GetInteger();
401         int threshold = values[6].GetInteger();
402         int sendq = values[7].GetInteger();
403         int recvq = values[8].GetInteger();
404         int localmax = values[9].GetInteger();
405         int globalmax = values[10].GetInteger();
406
407         if (*allow)
408         {
409                 ConnectClass c(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax);
410                 conf->Classes.push_back(c);
411         }
412         else
413         {
414                 ConnectClass c(deny);
415                 conf->Classes.push_back(c);
416         }
417
418         return true;
419 }
420
421 /* Callback called when there are no more <connect> tags
422  */
423 bool DoneConnect(ServerConfig* conf, const char* tag)
424 {
425         conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
426         return true;
427 }
428
429 /* Callback called before processing the first <uline> tag
430  */
431 bool InitULine(ServerConfig* conf, const char* tag)
432 {
433         conf->ulines.clear();
434         return true;
435 }
436
437 /* Callback called to process a single <uline> tag
438  */
439 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
440 {
441         const char* server = values[0].GetString();
442         conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
443         conf->ulines.push_back(server);
444         return true;
445 }
446
447 /* Callback called when there are no more <uline> tags
448  */
449 bool DoneULine(ServerConfig* conf, const char* tag)
450 {
451         return true;
452 }
453
454 /* Callback called before processing the first <module> tag
455  */
456 bool InitModule(ServerConfig* conf, const char* tag)
457 {
458         old_module_names.clear();
459         new_module_names.clear();
460         added_modules.clear();
461         removed_modules.clear();
462         for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
463         {
464                 old_module_names.push_back(*t);
465         }
466         return true;
467 }
468
469 /* Callback called to process a single <module> tag
470  */
471 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
472 {
473         const char* modname = values[0].GetString();
474         new_module_names.push_back(modname);
475         return true;
476 }
477
478 /* Callback called when there are no more <module> tags
479  */
480 bool DoneModule(ServerConfig* conf, const char* tag)
481 {
482         // now create a list of new modules that are due to be loaded
483         // and a seperate list of modules which are due to be unloaded
484         for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
485         {
486                 bool added = true;
487
488                 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
489                 {
490                         if (*old == *_new)
491                                 added = false;
492                 }
493
494                 if (added)
495                         added_modules.push_back(*_new);
496         }
497
498         for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
499         {
500                 bool removed = true;
501                 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
502                 {
503                         if (*newm == *oldm)
504                                 removed = false;
505                 }
506
507                 if (removed)
508                         removed_modules.push_back(*oldm);
509         }
510         return true;
511 }
512
513 /* Callback called before processing the first <banlist> tag
514  */
515 bool InitMaxBans(ServerConfig* conf, const char* tag)
516 {
517         conf->maxbans.clear();
518         return true;
519 }
520
521 /* Callback called to process a single <banlist> tag
522  */
523 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
524 {
525         const char* channel = values[0].GetString();
526         int limit = values[1].GetInteger();
527         conf->maxbans[channel] = limit;
528         return true;
529 }
530
531 /* Callback called when there are no more <banlist> tags.
532  */
533 bool DoneMaxBans(ServerConfig* conf, const char* tag)
534 {
535         return true;
536 }
537
538 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
539 {
540         ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
541         if (bail)
542         {
543                 /* Unneeded because of the ServerInstance->Log() aboive? */
544                 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
545                 InspIRCd::Exit(EXIT_STATUS_CONFIG);
546         }
547         else
548         {
549                 std::string errors = errormessage;
550                 std::string::size_type start;
551                 unsigned int prefixlen;
552                 start = 0;
553                 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
554                 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
555                 if (user)
556                 {
557                         user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
558                         while (start < errors.length())
559                         {
560                                 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
561                                 start += 510 - prefixlen;
562                         }
563                 }
564                 else
565                 {
566                         ServerInstance->WriteOpers("There were errors in the configuration file:");
567                         while (start < errors.length())
568                         {
569                                 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
570                                 start += 360;
571                         }
572                 }
573                 return;
574         }
575 }
576
577 void ServerConfig::Read(bool bail, userrec* user)
578 {
579         static char debug[MAXBUF];              /* Temporary buffer for debugging value */
580         static char maxkeep[MAXBUF];    /* Temporary buffer for WhoWasMaxKeep value */
581         static char softlimit[MAXBUF];  /* Temporary buffer for softlimit default */
582         static char somax[MAXBUF];              /* Temporary buffer for somax default */
583         int rem = 0, add = 0;           /* Number of modules added, number of modules removed */
584         std::ostringstream errstr;      /* String stream containing the error output */
585
586         /* These tags MUST occur and must ONLY occur once in the config file */
587         static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
588
589         /* These tags can occur ONCE or not at all */
590         InitialConfig Values[] = {
591                 {"options",     "softlimit",    itoa(MAXCLIENTS, softlimit, 10),                new ValueContainerUInt (&this->SoftLimit),              DT_INTEGER, ValidateSoftLimit},
592                 {"options",     "somaxconn",    itoa(SOMAXCONN, somax, 10),             new ValueContainerInt  (&this->MaxConn),                DT_INTEGER, ValidateMaxConn},
593                 {"server",      "name",         "",             new ValueContainerChar (this->ServerName),              DT_CHARPTR, ValidateServerName},
594                 {"server",      "description",  "",             new ValueContainerChar (this->ServerDesc),              DT_CHARPTR, NoValidation},
595                 {"server",      "network",      "",             new ValueContainerChar (this->Network),                 DT_CHARPTR, NoValidation},
596                 {"admin",       "name",         "",             new ValueContainerChar (this->AdminName),               DT_CHARPTR, NoValidation},
597                 {"admin",       "email",        "",             new ValueContainerChar (this->AdminEmail),              DT_CHARPTR, NoValidation},
598                 {"admin",       "nick",         "",             new ValueContainerChar (this->AdminNick),               DT_CHARPTR, NoValidation},
599                 {"files",       "motd",         "",             new ValueContainerChar (this->motd),                    DT_CHARPTR, ValidateMotd},
600                 {"files",       "rules",        "",             new ValueContainerChar (this->rules),                   DT_CHARPTR, ValidateRules},
601                 {"power",       "diepass",      "",             new ValueContainerChar (this->diepass),                 DT_CHARPTR, NoValidation},      
602                 {"power",       "pause",        "",             new ValueContainerInt  (&this->DieDelay),               DT_INTEGER, NoValidation},
603                 {"power",       "restartpass",  "",             new ValueContainerChar (this->restartpass),             DT_CHARPTR, NoValidation},
604                 {"options",     "prefixquit",   "",             new ValueContainerChar (this->PrefixQuit),              DT_CHARPTR, NoValidation},
605                 {"options",     "loglevel",     "",             new ValueContainerChar (debug),                         DT_CHARPTR, ValidateLogLevel},
606                 {"options",     "netbuffersize","10240",                new ValueContainerInt  (&this->NetBufferSize),          DT_INTEGER, ValidateNetBufferSize},
607                 {"options",     "maxwho",       "128",          new ValueContainerInt  (&this->MaxWhoResults),          DT_INTEGER, ValidateMaxWho},
608                 {"options",     "allowhalfop",  "",             new ValueContainerBool (&this->AllowHalfop),            DT_BOOLEAN, NoValidation},
609                 {"dns",         "server",       "",             new ValueContainerChar (this->DNSServer),               DT_CHARPTR, ValidateDnsServer},
610                 {"dns",         "timeout",      "5",            new ValueContainerInt  (&this->dns_timeout),            DT_INTEGER, NoValidation},
611                 {"options",     "moduledir",    "",             new ValueContainerChar (this->ModPath),                 DT_CHARPTR, ValidateModPath},
612                 {"disabled",    "commands",     "",             new ValueContainerChar (this->DisabledCommands),        DT_CHARPTR, NoValidation},
613                 {"options",     "userstats",    "",             new ValueContainerChar (this->UserStats),               DT_CHARPTR, NoValidation},
614                 {"options",     "customversion","",             new ValueContainerChar (this->CustomVersion),           DT_CHARPTR, NoValidation},
615                 {"options",     "hidesplits",   "",             new ValueContainerBool (&this->HideSplits),             DT_BOOLEAN, NoValidation},
616                 {"options",     "hidebans",     "",             new ValueContainerBool (&this->HideBans),               DT_BOOLEAN, NoValidation},
617                 {"options",     "hidewhois",    "",             new ValueContainerChar (this->HideWhoisServer),         DT_CHARPTR, NoValidation},
618                 {"options",     "operspywhois", "",             new ValueContainerBool (&this->OperSpyWhois),           DT_BOOLEAN, NoValidation},
619                 {"options",     "nouserdns",    "",             new ValueContainerBool (&this->NoUserDns),              DT_BOOLEAN, NoValidation},
620                 {"options",     "syntaxhints",  "",             new ValueContainerBool (&this->SyntaxHints),            DT_BOOLEAN, NoValidation},
621                 {"options",     "cyclehosts",   "",             new ValueContainerBool (&this->CycleHosts),             DT_BOOLEAN, NoValidation},
622                 {"options",     "ircumsgprefix","0",            new ValueContainerBool (&this->UndernetMsgPrefix),      DT_BOOLEAN, NoValidation},
623                 {"pid",         "file",         "",             new ValueContainerChar (this->PID),                     DT_CHARPTR, NoValidation},
624                 {"whowas",      "groupsize",    "10",           new ValueContainerInt  (&this->WhoWasGroupSize),        DT_INTEGER, NoValidation},
625                 {"whowas",      "maxgroups",    "10240",        new ValueContainerInt  (&this->WhoWasMaxGroups),        DT_INTEGER, NoValidation},
626                 {"whowas",      "maxkeep",      "3600",         new ValueContainerChar (maxkeep),                       DT_CHARPTR, ValidateWhoWas},
627                 {"die",         "value",        "",             new ValueContainerChar (this->DieValue),                DT_CHARPTR, NoValidation},
628                 {NULL}
629         };
630
631         /* These tags can occur multiple times, and therefore they have special code to read them
632          * which is different to the code for reading the singular tags listed above.
633          */
634         MultiConfig MultiValues[] = {
635
636                 {"connect",
637                                 {"allow",       "deny",         "password",     "timeout",      "pingfreq",     "flood",
638                                 "threshold",    "sendq",        "recvq",        "localmax",     "globalmax",    NULL},
639                                 {"", "", "", "", "", "", "", "", "", "", "", NULL},
640                                 {DT_CHARPTR,    DT_CHARPTR,     DT_CHARPTR,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
641                                  DT_INTEGER,    DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER},
642                                 InitConnect, DoConnect, DoneConnect},
643
644                 {"uline",
645                                 {"server",      NULL},
646                                 {"", NULL},
647                                 {DT_CHARPTR},
648                                 InitULine,DoULine,DoneULine},
649
650                 {"banlist",
651                                 {"chan",        "limit",        NULL},
652                                 {"", "", NULL},
653                                 {DT_CHARPTR,    DT_INTEGER},
654                                 InitMaxBans, DoMaxBans, DoneMaxBans},
655
656                 {"module",
657                                 {"name",        NULL},
658                                 {"", NULL},
659                                 {DT_CHARPTR},
660                                 InitModule, DoModule, DoneModule},
661
662                 {"badip",
663                                 {"reason",      "ipmask",       NULL},
664                                 {"", "", NULL},
665                                 {DT_CHARPTR,    DT_CHARPTR},
666                                 InitXLine, DoZLine, DoneXLine},
667
668                 {"badnick",
669                                 {"reason",      "nick",         NULL},
670                                 {"", "", NULL},
671                                 {DT_CHARPTR,    DT_CHARPTR},
672                                 InitXLine, DoQLine, DoneXLine},
673
674                 {"badhost",
675                                 {"reason",      "host",         NULL},
676                                 {"", "", NULL},
677                                 {DT_CHARPTR,    DT_CHARPTR},
678                                 InitXLine, DoKLine, DoneXLine},
679
680                 {"exception",
681                                 {"reason",      "host",         NULL},
682                                 {"", "", NULL},
683                                 {DT_CHARPTR,    DT_CHARPTR},
684                                 InitXLine, DoELine, DoneXLine},
685
686                 {"type",
687                                 {"name",        "classes",      NULL},
688                                 {"", "", NULL},
689                                 {DT_CHARPTR,    DT_CHARPTR},
690                                 InitTypes, DoType, DoneClassesAndTypes},
691
692                 {"class",
693                                 {"name",        "commands",     NULL},
694                                 {"", "", NULL},
695                                 {DT_CHARPTR,    DT_CHARPTR},
696                                 InitClasses, DoClass, DoneClassesAndTypes},
697
698                 {NULL}
699         };
700
701         include_stack.clear();
702
703         /* Load and parse the config file, if there are any errors then explode */
704         
705         /* Make a copy here so if it fails then we can carry on running with an unaffected config */
706         ConfigDataHash newconfig;
707         
708         if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
709         {
710                 /* If we succeeded, set the ircd config to the new one */
711                 this->config_data = newconfig;  
712         }
713         else
714         {
715                 ReportConfigError(errstr.str(), bail, user);
716                 return;
717         }
718
719         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
720         try
721         {
722                 /* Check we dont have more than one of singular tags, or any of them missing
723                  */
724                 for (int Index = 0; Once[Index]; Index++)
725                         if (!CheckOnce(Once[Index], bail, user))
726                                 return;
727
728                 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
729                  */
730                 for (int Index = 0; Values[Index].tag; Index++)
731                 {
732                         char item[MAXBUF];
733                         int dt = Values[Index].datatype;
734                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
735                         dt &= ~DT_ALLOW_NEWLINE;
736
737                         ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
738                         ValueItem vi(item);
739
740                         Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi);
741
742                         switch (Values[Index].datatype)
743                         {
744                                 case DT_CHARPTR:
745                                 {
746                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
747                                         vcc->Set(vi.GetString(), strlen(vi.GetString()));
748                                 }
749                                 break;
750                                 case DT_INTEGER:
751                                 {
752                                         int val = vi.GetInteger();
753                                         ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
754                                         vci->Set(&val, sizeof(int));
755                                 }
756                                 break;
757                                 case DT_BOOLEAN:
758                                 {
759                                         bool val = vi.GetBool();
760                                         ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
761                                         vcb->Set(&val, sizeof(bool));
762                                 }
763                                 break;
764                                 default:
765                                         /* You don't want to know what happens if someones bad code sends us here. */
766                                 break;
767                         }
768         
769                         /* We're done with this now */
770                         delete Values[Index].val;
771                 }
772
773                 /* Read the multiple-tag items (class tags, connect tags, etc)
774                  * and call the callbacks associated with them. We have three
775                  * callbacks for these, a 'start', 'item' and 'end' callback.
776                  */
777                 for (int Index = 0; MultiValues[Index].tag; Index++)
778                 {
779                         MultiValues[Index].init_function(this, MultiValues[Index].tag);
780
781                         int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
782
783                         for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
784                         {
785                                 ValueList vl;
786                                 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
787                                 {
788                                         int dt = MultiValues[Index].datatype[valuenum];
789                                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
790                                         dt &= ~DT_ALLOW_NEWLINE;
791
792                                         switch (dt)
793                                         {
794                                                 case DT_CHARPTR:
795                                                 {
796                                                         char item[MAXBUF];
797                                                         if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
798                                                                 vl.push_back(ValueItem(item));
799                                                         else
800                                                                 vl.push_back(ValueItem(""));
801                                                 }
802                                                 break;
803                                                 case DT_INTEGER:
804                                                 {
805                                                         int item = 0;
806                                                         if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
807                                                                 vl.push_back(ValueItem(item));
808                                                         else
809                                                                 vl.push_back(ValueItem(0));
810                                                 }
811                                                 break;
812                                                 case DT_BOOLEAN:
813                                                 {
814                                                         bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
815                                                         vl.push_back(ValueItem(item));
816                                                 }
817                                                 break;
818                                                 default:
819                                                         /* Someone was smoking craq if we got here, and we're all gonna die. */
820                                                 break;
821                                         }
822                                 }
823         
824                                 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
825                         }
826         
827                         MultiValues[Index].finish_function(this, MultiValues[Index].tag);
828                 }
829
830         }
831
832         catch (CoreException &ce)
833         {
834                 ReportConfigError(ce.GetReason(), bail, user);
835                 return;
836         }
837
838         // write once here, to try it out and make sure its ok
839         ServerInstance->WritePID(this->PID);
840
841         ServerInstance->Log(DEFAULT,"Done reading configuration file.");
842
843         /* If we're rehashing, let's load any new modules, and unload old ones
844          */
845         if (!bail)
846         {
847                 int found_ports = 0;
848                 FailedPortList pl;
849                 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
850
851                 if (pl.size())
852                 {
853                         user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
854                         user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
855                         int j = 1;
856                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
857                         {
858                                 user->WriteServ("NOTICE %s :*** %d.   IP: %s     Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
859                         }
860                 }
861
862                 if (!removed_modules.empty())
863                 {
864                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
865                         {
866                                 if (ServerInstance->UnloadModule(removing->c_str()))
867                                 {
868                                         ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
869
870                                         if (user)
871                                                 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
872
873                                         rem++;
874                                 }
875                                 else
876                                 {
877                                         if (user)
878                                                 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
879                                 }
880                         }
881                 }
882
883                 if (!added_modules.empty())
884                 {
885                         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
886                         {
887                                 if (ServerInstance->LoadModule(adding->c_str()))
888                                 {
889                                         ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
890         
891                                         if (user)
892                                                 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
893         
894                                         add++;
895                                 }
896                                 else
897                                 {
898                                         if (user)
899                                                 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
900                                 }
901                         }
902                 }
903
904                 ServerInstance->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());
905         }
906 }
907
908 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
909 {
910         std::ifstream conf(filename);
911         std::string line;
912         char ch;
913         long linenumber;
914         bool in_tag;
915         bool in_quote;
916         bool in_comment;
917         
918         linenumber = 1;
919         in_tag = false;
920         in_quote = false;
921         in_comment = false;
922         
923         /* Check if the file open failed first */
924         if (!conf)
925         {
926                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
927                 return false;
928         }
929         
930         /* Fix the chmod of the file to restrict it to the current user and group */
931         chmod(filename,0600);
932         
933         for (unsigned int t = 0; t < include_stack.size(); t++)
934         {
935                 if (std::string(filename) == include_stack[t])
936                 {
937                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
938                         return false;
939                 }
940         }
941         
942         /* It's not already included, add it to the list of files we've loaded */
943         include_stack.push_back(filename);
944         
945         /* Start reading characters... */       
946         while(conf.get(ch))
947         {
948                 /*
949                  * Here we try and get individual tags on separate lines,
950                  * this would be so easy if we just made people format
951                  * their config files like that, but they don't so...
952                  * We check for a '<' and then know the line is over when
953                  * we get a '>' not inside quotes. If we find two '<' and
954                  * no '>' then die with an error.
955                  */
956                 
957                 if((ch == '#') && !in_quote)
958                         in_comment = true;
959                 
960                 /*if(((ch == '\n') || (ch == '\r')) && in_quote)
961                 {
962                         errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
963                         return false;
964                 }*/
965                 
966                 switch(ch)
967                 {
968                         case '\n':
969                                 if (in_quote)
970                                 {
971                                         ServerInstance->Log(DEBUG, "Got \\n inside value");
972                                         line += '\n';
973                                 }
974                                 linenumber++;
975                         case '\r':
976                                 if (!in_quote)
977                                         in_comment = false;
978                         case '\0':
979                                 continue;
980                         case '\t':
981                                 ch = ' ';
982                 }
983                 
984                 if(in_comment)
985                         continue;
986
987                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
988                  * Note that this WILL NOT usually allow insertion of newlines,
989                  * because a newline is two characters long. Use it primarily to
990                  * insert the " symbol.
991                  *
992                  * Note that this also involves a further check when parsing the line,
993                  * which can be found below.
994                  */
995                 if ((ch == '\\') && (in_quote) && (in_tag))
996                 {
997                         line += ch;
998                         ServerInstance->Log(DEBUG,"Escape sequence in config line.");
999                         char real_character;
1000                         if (conf.get(real_character))
1001                         {
1002                                 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
1003                                 if (real_character == 'n')
1004                                         real_character = '\n';
1005                                 line += real_character;
1006                                 continue;
1007                         }
1008                         else
1009                         {
1010                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1011                                 return false;
1012                         }
1013                 }
1014
1015                 if (ch != '\r')
1016                         line += ch;
1017                 
1018                 if(ch == '<')
1019                 {
1020                         if(in_tag)
1021                         {
1022                                 if(!in_quote)
1023                                 {
1024                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1025                                         return false;
1026                                 }
1027                         }
1028                         else
1029                         {
1030                                 if(in_quote)
1031                                 {
1032                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1033                                         return false;
1034                                 }
1035                                 else
1036                                 {
1037                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1038                                         in_tag = true;
1039                                 }
1040                         }
1041                 }
1042                 else if(ch == '"')
1043                 {
1044                         if(in_tag)
1045                         {
1046                                 if(in_quote)
1047                                 {
1048                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1049                                         in_quote = false;
1050                                 }
1051                                 else
1052                                 {
1053                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1054                                         in_quote = true;
1055                                 }
1056                         }
1057                         else
1058                         {
1059                                 if(in_quote)
1060                                 {
1061                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1062                                 }
1063                                 else
1064                                 {
1065                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1066                                 }
1067                         }
1068                 }
1069                 else if(ch == '>')
1070                 {
1071                         if(!in_quote)
1072                         {
1073                                 if(in_tag)
1074                                 {
1075                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
1076                                         in_tag = false;
1077
1078                                         /*
1079                                          * If this finds an <include> then ParseLine can simply call
1080                                          * LoadConf() and load the included config into the same ConfigDataHash
1081                                          */
1082                                         
1083                                         if(!this->ParseLine(target, line, linenumber, errorstream))
1084                                                 return false;
1085                                         
1086                                         line.clear();
1087                                 }
1088                                 else
1089                                 {
1090                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1091                                         return false;
1092                                 }
1093                         }
1094                 }
1095         }
1096         
1097         return true;
1098 }
1099
1100 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1101 {
1102         return this->LoadConf(target, filename.c_str(), errorstream);
1103 }
1104
1105 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1106 {
1107         std::string tagname;
1108         std::string current_key;
1109         std::string current_value;
1110         KeyValList results;
1111         bool got_name;
1112         bool got_key;
1113         bool in_quote;
1114         
1115         got_name = got_key = in_quote = false;
1116
1117         //std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1118         
1119         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1120         {
1121                 if(!got_name)
1122                 {
1123                         /* We don't know the tag name yet. */
1124                         
1125                         if(*c != ' ')
1126                         {
1127                                 if(*c != '<')
1128                                 {
1129                                         tagname += *c;
1130                                 }
1131                         }
1132                         else
1133                         {
1134                                 /* We got to a space, we should have the tagname now. */
1135                                 if(tagname.length())
1136                                 {
1137                                         got_name = true;
1138                                 }
1139                         }
1140                 }
1141                 else
1142                 {
1143                         /* We have the tag name */
1144                         if (!got_key)
1145                         {
1146                                 /* We're still reading the key name */
1147                                 if (*c != '=')
1148                                 {
1149                                         if (*c != ' ')
1150                                         {
1151                                                 current_key += *c;
1152                                         }
1153                                 }
1154                                 else
1155                                 {
1156                                         /* We got an '=', end of the key name. */
1157                                         got_key = true;
1158                                 }
1159                         }
1160                         else
1161                         {
1162                                 /* We have the key name, now we're looking for quotes and the value */
1163
1164                                 /* Correctly handle escaped characters here.
1165                                  * See the XXX'ed section above.
1166                                  */
1167                                 if ((*c == '\\') && (in_quote))
1168                                 {
1169                                         c++;
1170                                         if (*c == 'n')
1171                                                 current_value += '\n';
1172                                         else
1173                                                 current_value += *c;
1174                                         continue;
1175                                 }
1176                                 else if ((*c == '\n') && (in_quote))
1177                                 {
1178                                         /* Got a 'real' \n, treat it as part of the value */
1179                                         current_value += '\n';
1180                                         continue;
1181                                 }
1182                                 else if ((*c == '\r') && (in_quote))
1183                                         /* Got a \r, drop it */
1184                                         continue;
1185
1186                                 if (*c == '"')
1187                                 {
1188                                         if (!in_quote)
1189                                         {
1190                                                 /* We're not already in a quote. */
1191                                                 in_quote = true;
1192                                         }
1193                                         else
1194                                         {
1195                                                 /* Leaving quotes, we have the value */
1196                                                 results.push_back(KeyVal(current_key, current_value));
1197
1198                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1199                                                 
1200                                                 in_quote = false;
1201                                                 got_key = false;
1202                                                 
1203                                                 if((tagname == "include") && (current_key == "file"))
1204                                                 {
1205                                                         if(!this->DoInclude(target, current_value, errorstream))
1206                                                                 return false;
1207                                                 }
1208                                                 
1209                                                 current_key.clear();
1210                                                 current_value.clear();
1211                                         }
1212                                 }
1213                                 else
1214                                 {
1215                                         if(in_quote)
1216                                         {
1217                                                 current_value += *c;
1218                                         }
1219                                 }
1220                         }
1221                 }
1222         }
1223         
1224         /* Finished parsing the tag, add it to the config hash */
1225         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1226         
1227         return true;
1228 }
1229
1230 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1231 {
1232         std::string confpath;
1233         std::string newfile;
1234         std::string::size_type pos;
1235         
1236         confpath = CONFIG_FILE;
1237         newfile = file;
1238         
1239         for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1240         {
1241                 if (*c == '\\')
1242                 {
1243                         *c = '/';
1244                 }
1245         }
1246
1247         if (file[0] != '/')
1248         {
1249                 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1250                 {
1251                         /* Leaves us with just the path */
1252                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1253                 }
1254                 else
1255                 {
1256                         errorstream << "Couldn't get config path from: " << confpath << std::endl;
1257                         return false;
1258                 }
1259         }
1260         
1261         return LoadConf(target, newfile, errorstream);
1262 }
1263
1264 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1265 {
1266         return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1267 }
1268
1269 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1270 {
1271         std::string value;
1272         bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1273         strlcpy(result, value.c_str(), length);
1274         return r;
1275 }
1276
1277 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1278 {
1279         return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1280 }
1281
1282 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1283 {
1284         ConfigDataHash::size_type pos = index;
1285         if((pos >= 0) && (pos < target.count(tag)))
1286         {
1287                 ConfigDataHash::iterator iter = target.find(tag);
1288
1289                 for(int i = 0; i < index; i++)
1290                         iter++;
1291
1292                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1293                 {
1294                         if(j->first == var)
1295                         {
1296                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1297                                 {
1298                                         ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1299                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1300                                                 if (*n == '\n')
1301                                                         *n = ' ';
1302                                 }
1303                                 else
1304                                 {
1305                                         result = j->second;
1306                                         return true;
1307                                 }
1308                         }
1309                 }
1310                 if (!default_value.empty())
1311                 {
1312                         result = default_value;
1313                         ServerInstance->Log(DEBUG, "No config option for '%s' in tag <%s> using default: %s", var.c_str(), tag.c_str(), default_value.c_str());
1314                         return true;
1315                 }
1316         }
1317         else if(pos == 0)
1318         {
1319                 if (!default_value.empty())
1320                 {
1321                         result = default_value;
1322                         ServerInstance->Log(DEBUG, "No <%s:%s> tags in config file using default: %s", tag.c_str(), var.c_str(), default_value.c_str());
1323                         return true;
1324                 }
1325                 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1326         }
1327         else
1328         {
1329                 ServerInstance->Log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1330         }
1331         return false;
1332 }
1333         
1334 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1335 {
1336         return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1337 }
1338
1339 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1340 {
1341         return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1342 }
1343
1344 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1345 {
1346         return ConfValueInteger(target, tag, var, "", index, result);
1347 }
1348
1349 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1350 {
1351         std::string value;
1352         std::istringstream stream;
1353         bool r = ConfValue(target, tag, var, default_value, index, value);
1354         stream.str(value);
1355         if(!(stream >> result))
1356                 return false;
1357         return r;
1358 }
1359
1360         
1361 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1362 {
1363         return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1364 }
1365
1366 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1367 {
1368         return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1369 }
1370
1371 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1372 {
1373         return ConfValueBool(target, tag, var, "", index);
1374 }
1375
1376 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1377 {
1378         std::string result;
1379         if(!ConfValue(target, tag, var, default_value, index, result))
1380                 return false;
1381         
1382         return ((result == "yes") || (result == "true") || (result == "1"));
1383 }
1384         
1385 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1386 {
1387         return target.count(tag);
1388 }
1389
1390 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1391 {
1392         return target.count(tag);
1393 }
1394         
1395 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1396 {
1397         return ConfVarEnum(target, std::string(tag), index);
1398 }
1399
1400 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1401 {
1402         ConfigDataHash::size_type pos = index;
1403         
1404         if((pos >= 0) && (pos < target.count(tag)))
1405         {
1406                 ConfigDataHash::const_iterator iter = target.find(tag);
1407                 
1408                 for(int i = 0; i < index; i++)
1409                         iter++;
1410                 
1411                 return iter->second.size();
1412         }
1413         else if(pos == 0)
1414         {
1415                 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1416         }
1417         else
1418         {
1419                 ServerInstance->Log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1420         }
1421         
1422         return 0;
1423 }
1424
1425 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1426  */
1427 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1428 {
1429         FILE* file = NULL;
1430         char linebuf[MAXBUF];
1431
1432         F.clear();
1433         
1434         if (*fname != '/')
1435         {
1436                 std::string::size_type pos;
1437                 std::string confpath = CONFIG_FILE;
1438                 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1439                 {
1440                         /* Leaves us with just the path */
1441                         std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1442                         file =  fopen(newfile.c_str(), "r");
1443                         
1444                 }
1445         }
1446         else
1447                 file =  fopen(fname, "r");
1448
1449         if (file)
1450         {
1451                 while (!feof(file))
1452                 {
1453                         if (fgets(linebuf, sizeof(linebuf), file))
1454                                 linebuf[strlen(linebuf)-1] = 0;
1455                         else
1456                                 *linebuf = 0;
1457
1458                         if (!feof(file))
1459                         {
1460                                 F.push_back(*linebuf ? linebuf : " ");
1461                         }
1462                 }
1463
1464                 fclose(file);
1465         }
1466         else
1467                 return false;
1468
1469         return true;
1470 }
1471
1472 bool ServerConfig::FileExists(const char* file)
1473 {
1474         FILE *input;
1475         if ((input = fopen (file, "r")) == NULL)
1476         {
1477                 return false;
1478         }
1479         else
1480         {
1481                 fclose(input);
1482                 return true;
1483         }
1484 }
1485
1486 char* ServerConfig::CleanFilename(char* name)
1487 {
1488         char* p = name + strlen(name);
1489         while ((p != name) && (*p != '/')) p--;
1490         return (p != name ? ++p : p);
1491 }
1492
1493
1494 bool ServerConfig::DirValid(const char* dirandfile)
1495 {
1496         char work[MAXBUF];
1497         char buffer[MAXBUF];
1498         char otherdir[MAXBUF];
1499         int p;
1500
1501         strlcpy(work, dirandfile, MAXBUF);
1502         p = strlen(work);
1503
1504         // we just want the dir
1505         while (*work)
1506         {
1507                 if (work[p] == '/')
1508                 {
1509                         work[p] = '\0';
1510                         break;
1511                 }
1512
1513                 work[p--] = '\0';
1514         }
1515
1516         // Get the current working directory
1517         if (getcwd(buffer, MAXBUF ) == NULL )
1518                 return false;
1519
1520         if (chdir(work) == -1)
1521                 return false;
1522
1523         if (getcwd(otherdir, MAXBUF ) == NULL )
1524                 return false;
1525
1526         if (chdir(buffer) == -1)
1527                 return false;
1528
1529         size_t t = strlen(work);
1530
1531         if (strlen(otherdir) >= t)
1532         {
1533                 otherdir[t] = '\0';
1534
1535                 if (!strcmp(otherdir,work))
1536                 {
1537                         return true;
1538                 }
1539
1540                 return false;
1541         }
1542         else
1543         {
1544                 return false;
1545         }
1546 }
1547
1548 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1549 {
1550         char work[MAXBUF];
1551         char buffer[MAXBUF];
1552         char otherdir[MAXBUF];
1553         int p;
1554
1555         strlcpy(work,argv[0],MAXBUF);
1556         p = strlen(work);
1557
1558         // we just want the dir
1559         while (*work)
1560         {
1561                 if (work[p] == '/')
1562                 {
1563                         work[p] = '\0';
1564                         break;
1565                 }
1566
1567                 work[p--] = '\0';
1568         }
1569
1570         // Get the current working directory
1571         if (getcwd(buffer, MAXBUF) == NULL)
1572                 return "";
1573
1574         if (chdir(work) == -1)
1575                 return "";
1576
1577         if (getcwd(otherdir, MAXBUF) == NULL)
1578                 return "";
1579
1580         if (chdir(buffer) == -1)
1581                 return "";
1582
1583         return otherdir;
1584 }
1585
1586 InspIRCd* ServerConfig::GetInstance()
1587 {
1588         return ServerInstance;
1589 }
1590
1591
1592 ValueItem::ValueItem(int value)
1593 {
1594         std::stringstream n;
1595         n << value;
1596         v = n.str();
1597 }
1598
1599 ValueItem::ValueItem(bool value)
1600 {
1601         std::stringstream n;
1602         n << value;
1603         v = n.str();
1604 }
1605
1606 ValueItem::ValueItem(char* value)
1607 {
1608         v = value;
1609 }
1610
1611 void ValueItem::Set(char* value)
1612 {
1613         v = value;
1614 }
1615
1616 void ValueItem::Set(const char* value)
1617 {
1618         v = value;
1619 }
1620
1621 void ValueItem::Set(int value)
1622 {
1623         std::stringstream n;
1624         n << value;
1625         v = n.str();
1626 }
1627
1628 int ValueItem::GetInteger()
1629 {
1630         if (v.empty())
1631                 return 0;
1632         return atoi(v.c_str());
1633 }
1634
1635 char* ValueItem::GetString()
1636 {
1637         return (char*)v.c_str();
1638 }
1639
1640 bool ValueItem::GetBool()
1641 {
1642         return (GetInteger() || v == "yes" || v == "true");
1643 }
1644