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