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