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