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