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