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