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