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