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