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