]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
ccf88ea0d7b42488817b344eb10ab6b93c1174a4
[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
408         if (*allow)
409         {
410                 ConnectClass c(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax);
411                 conf->Classes.push_back(c);
412         }
413         else
414         {
415                 ConnectClass c(deny);
416                 conf->Classes.push_back(c);
417         }
418
419         return true;
420 }
421
422 /* Callback called when there are no more <connect> tags
423  */
424 bool DoneConnect(ServerConfig* conf, const char* tag)
425 {
426         return true;
427 }
428
429 /* Callback called before processing the first <uline> tag
430  */
431 bool InitULine(ServerConfig* conf, const char* tag)
432 {
433         conf->ulines.clear();
434         return true;
435 }
436
437 /* Callback called to process a single <uline> tag
438  */
439 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
440 {
441         const char* server = values[0].GetString();
442         const bool silent = values[1].GetBool();
443         conf->ulines[server] = silent;
444         return true;
445 }
446
447 /* Callback called when there are no more <uline> tags
448  */
449 bool DoneULine(ServerConfig* conf, const char* tag)
450 {
451         return true;
452 }
453
454 /* Callback called before processing the first <module> tag
455  */
456 bool InitModule(ServerConfig* conf, const char* tag)
457 {
458         old_module_names.clear();
459         new_module_names.clear();
460         added_modules.clear();
461         removed_modules.clear();
462         for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
463         {
464                 old_module_names.push_back(*t);
465         }
466         return true;
467 }
468
469 /* Callback called to process a single <module> tag
470  */
471 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
472 {
473         const char* modname = values[0].GetString();
474         new_module_names.push_back(modname);
475         return true;
476 }
477
478 /* Callback called when there are no more <module> tags
479  */
480 bool DoneModule(ServerConfig* conf, const char* tag)
481 {
482         // now create a list of new modules that are due to be loaded
483         // and a seperate list of modules which are due to be unloaded
484         for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
485         {
486                 bool added = true;
487
488                 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
489                 {
490                         if (*old == *_new)
491                                 added = false;
492                 }
493
494                 if (added)
495                         added_modules.push_back(*_new);
496         }
497
498         for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
499         {
500                 bool removed = true;
501                 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
502                 {
503                         if (*newm == *oldm)
504                                 removed = false;
505                 }
506
507                 if (removed)
508                         removed_modules.push_back(*oldm);
509         }
510         return true;
511 }
512
513 /* Callback called before processing the first <banlist> tag
514  */
515 bool InitMaxBans(ServerConfig* conf, const char* tag)
516 {
517         conf->maxbans.clear();
518         return true;
519 }
520
521 /* Callback called to process a single <banlist> tag
522  */
523 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
524 {
525         const char* channel = values[0].GetString();
526         int limit = values[1].GetInteger();
527         conf->maxbans[channel] = limit;
528         return true;
529 }
530
531 /* Callback called when there are no more <banlist> tags.
532  */
533 bool DoneMaxBans(ServerConfig* conf, const char* tag)
534 {
535         return true;
536 }
537
538 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
539 {
540         ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
541         if (bail)
542         {
543                 /* Unneeded because of the ServerInstance->Log() aboive? */
544                 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
545                 ServerInstance->Exit(EXIT_STATUS_CONFIG);
546         }
547         else
548         {
549                 std::string errors = errormessage;
550                 std::string::size_type start;
551                 unsigned int prefixlen;
552                 start = 0;
553                 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
554                 if (user)
555                 {
556                         prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
557                         user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
558                         while (start < errors.length())
559                         {
560                                 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
561                                 start += 510 - prefixlen;
562                         }
563                 }
564                 else
565                 {
566                         ServerInstance->WriteOpers("There were errors in the configuration file:");
567                         while (start < errors.length())
568                         {
569                                 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
570                                 start += 360;
571                         }
572                 }
573                 return;
574         }
575 }
576
577 void ServerConfig::Read(bool bail, userrec* user)
578 {
579         static char debug[MAXBUF];      /* Temporary buffer for debugging value */
580         static char maxkeep[MAXBUF];    /* Temporary buffer for WhoWasMaxKeep value */
581         static char hidemodes[MAXBUF];  /* Modes to not allow listing from users below halfop */
582         static char exemptchanops[MAXBUF];      /* Exempt channel ops from these modes */
583         int rem = 0, add = 0;           /* Number of modules added, number of modules removed */
584         std::ostringstream errstr;      /* String stream containing the error output */
585
586         /* These tags MUST occur and must ONLY occur once in the config file */
587         static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
588
589         /* These tags can occur ONCE or not at all */
590         InitialConfig Values[] = {
591                 {"options",     "softlimit",    MAXCLIENTS_S,           new ValueContainerUInt (&this->SoftLimit),              DT_INTEGER, ValidateSoftLimit},
592                 {"options",     "somaxconn",    SOMAXCONN_S,            new ValueContainerInt  (&this->MaxConn),                DT_INTEGER, ValidateMaxConn},
593                 {"options",     "moronbanner",  "Youre banned!",        new ValueContainerChar (this->MoronBanner),             DT_CHARPTR, NoValidation},
594                 {"server",      "name",         "",                     new ValueContainerChar (this->ServerName),              DT_CHARPTR, ValidateServerName},
595                 {"server",      "description",  "Configure Me",         new ValueContainerChar (this->ServerDesc),              DT_CHARPTR, NoValidation},
596                 {"server",      "network",      "Network",              new ValueContainerChar (this->Network),                 DT_CHARPTR, NoValidation},
597                 {"admin",       "name",         "",                     new ValueContainerChar (this->AdminName),               DT_CHARPTR, NoValidation},
598                 {"admin",       "email",        "Mis@configu.red",      new ValueContainerChar (this->AdminEmail),              DT_CHARPTR, NoValidation},
599                 {"admin",       "nick",         "Misconfigured",        new ValueContainerChar (this->AdminNick),               DT_CHARPTR, NoValidation},
600                 {"files",       "motd",         "",                     new ValueContainerChar (this->motd),                    DT_CHARPTR, ValidateMotd},
601                 {"files",       "rules",        "",                     new ValueContainerChar (this->rules),                   DT_CHARPTR, ValidateRules},
602                 {"power",       "diepass",      "",                     new ValueContainerChar (this->diepass),                 DT_CHARPTR, ValidateNotEmpty},
603                 {"power",       "pause",        "",                     new ValueContainerInt  (&this->DieDelay),               DT_INTEGER, NoValidation},
604                 {"power",       "restartpass",  "",                     new ValueContainerChar (this->restartpass),             DT_CHARPTR, ValidateNotEmpty},
605                 {"options",     "prefixquit",   "",                     new ValueContainerChar (this->PrefixQuit),              DT_CHARPTR, NoValidation},
606                 {"options",     "suffixquit",   "",                     new ValueContainerChar (this->SuffixQuit),              DT_CHARPTR, NoValidation},
607                 {"options",     "fixedquit",    "",                     new ValueContainerChar (this->FixedQuit),               DT_CHARPTR, NoValidation},
608                 {"options",     "loglevel",     "default",              new ValueContainerChar (debug),                         DT_CHARPTR, ValidateLogLevel},
609                 {"options",     "netbuffersize","10240",                new ValueContainerInt  (&this->NetBufferSize),          DT_INTEGER, ValidateNetBufferSize},
610                 {"options",     "maxwho",       "128",                  new ValueContainerInt  (&this->MaxWhoResults),          DT_INTEGER, ValidateMaxWho},
611                 {"options",     "allowhalfop",  "0",                    new ValueContainerBool (&this->AllowHalfop),            DT_BOOLEAN, NoValidation},
612                 {"dns",         "server",       "",                     new ValueContainerChar (this->DNSServer),               DT_CHARPTR, DNSServerValidator},
613                 {"dns",         "timeout",      "5",                    new ValueContainerInt  (&this->dns_timeout),            DT_INTEGER, NoValidation},
614                 {"options",     "moduledir",    MOD_PATH,               new ValueContainerChar (this->ModPath),                 DT_CHARPTR, NoValidation},
615                 {"disabled",    "commands",     "",                     new ValueContainerChar (this->DisabledCommands),        DT_CHARPTR, NoValidation},
616                 {"options",     "userstats",    "",                     new ValueContainerChar (this->UserStats),               DT_CHARPTR, NoValidation},
617                 {"options",     "customversion","",                     new ValueContainerChar (this->CustomVersion),           DT_CHARPTR, NoValidation},
618                 {"options",     "hidesplits",   "0",                    new ValueContainerBool (&this->HideSplits),             DT_BOOLEAN, NoValidation},
619                 {"options",     "hidebans",     "0",                    new ValueContainerBool (&this->HideBans),               DT_BOOLEAN, NoValidation},
620                 {"options",     "hidewhois",    "",                     new ValueContainerChar (this->HideWhoisServer),         DT_CHARPTR, NoValidation},
621                 {"options",     "hidekills",    "",                     new ValueContainerChar (this->HideKillsServer),         DT_CHARPTR, NoValidation},
622                 {"options",     "operspywhois", "0",                    new ValueContainerBool (&this->OperSpyWhois),           DT_BOOLEAN, NoValidation},
623                 {"options",     "nouserdns",    "0",                    new ValueContainerBool (&this->NoUserDns),              DT_BOOLEAN, NoValidation},
624                 {"options",     "syntaxhints",  "0",                    new ValueContainerBool (&this->SyntaxHints),            DT_BOOLEAN, NoValidation},
625                 {"options",     "cyclehosts",   "0",                    new ValueContainerBool (&this->CycleHosts),             DT_BOOLEAN, NoValidation},
626                 {"options",     "ircumsgprefix","0",                    new ValueContainerBool (&this->UndernetMsgPrefix),      DT_BOOLEAN, NoValidation},
627                 {"options",     "announceinvites", "1",                 new ValueContainerBool (&this->AnnounceInvites),        DT_BOOLEAN, NoValidation},
628                 {"options",     "hostintopic",  "1",                    new ValueContainerBool (&this->FullHostInTopic),        DT_BOOLEAN, NoValidation},
629                 {"options",     "hidemodes",    "",                     new ValueContainerChar (hidemodes),                     DT_CHARPTR, ValidateModeLists},
630                 {"options",     "exemptchanops","",                     new ValueContainerChar (exemptchanops),                 DT_CHARPTR, ValidateExemptChanOps},
631                 {"options",     "defaultmodes", "nt",                   new ValueContainerChar (this->DefaultModes),            DT_CHARPTR, NoValidation},
632                 {"pid",         "file",         "",                     new ValueContainerChar (this->PID),                     DT_CHARPTR, NoValidation},
633                 {"whowas",      "groupsize",    "10",                   new ValueContainerInt  (&this->WhoWasGroupSize),        DT_INTEGER, NoValidation},
634                 {"whowas",      "maxgroups",    "10240",                new ValueContainerInt  (&this->WhoWasMaxGroups),        DT_INTEGER, NoValidation},
635                 {"whowas",      "maxkeep",      "3600",                 new ValueContainerChar (maxkeep),                       DT_CHARPTR, ValidateWhoWas},
636                 {"die",         "value",        "",                     new ValueContainerChar (this->DieValue),                DT_CHARPTR, NoValidation},
637                 {"channels",    "users",        "20",                   new ValueContainerUInt (&this->MaxChans),               DT_INTEGER, NoValidation},
638                 {"channels",    "opers",        "60",                   new ValueContainerUInt (&this->OperMaxChans),           DT_INTEGER, NoValidation},
639                 {NULL}
640         };
641
642         /* These tags can occur multiple times, and therefore they have special code to read them
643          * which is different to the code for reading the singular tags listed above.
644          */
645         MultiConfig MultiValues[] = {
646
647                 {"connect",
648                                 {"allow",       "deny",         "password",     "timeout",      "pingfreq",     "flood",
649                                 "threshold",    "sendq",        "recvq",        "localmax",     "globalmax",    "port",
650                                 NULL},
651                                 {"",            "",             "",             "",             "120",          "",
652                                  "",            "",             "",             "3",            "3",            "0",
653                                  NULL},
654                                 {DT_CHARPTR,    DT_CHARPTR,     DT_CHARPTR,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
655                                  DT_INTEGER,    DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER},
656                                 InitConnect, DoConnect, DoneConnect},
657
658                 {"uline",
659                                 {"server",      "silent",       NULL},
660                                 {"",            "0",            NULL},
661                                 {DT_CHARPTR,    DT_BOOLEAN},
662                                 InitULine,DoULine,DoneULine},
663
664                 {"banlist",
665                                 {"chan",        "limit",        NULL},
666                                 {"",            "",             NULL},
667                                 {DT_CHARPTR,    DT_INTEGER},
668                                 InitMaxBans, DoMaxBans, DoneMaxBans},
669
670                 {"module",
671                                 {"name",        NULL},
672                                 {"",            NULL},
673                                 {DT_CHARPTR},
674                                 InitModule, DoModule, DoneModule},
675
676                 {"badip",
677                                 {"reason",      "ipmask",       NULL},
678                                 {"No reason",   "",             NULL},
679                                 {DT_CHARPTR,    DT_CHARPTR},
680                                 InitXLine, DoZLine, DoneZLine},
681
682                 {"badnick",
683                                 {"reason",      "nick",         NULL},
684                                 {"No reason",   "",             NULL},
685                                 {DT_CHARPTR,    DT_CHARPTR},
686                                 InitXLine, DoQLine, DoneQLine},
687
688                 {"badhost",
689                                 {"reason",      "host",         NULL},
690                                 {"No reason",   "",             NULL},
691                                 {DT_CHARPTR,    DT_CHARPTR},
692                                 InitXLine, DoKLine, DoneKLine},
693
694                 {"exception",
695                                 {"reason",      "host",         NULL},
696                                 {"No reason",   "",             NULL},
697                                 {DT_CHARPTR,    DT_CHARPTR},
698                                 InitXLine, DoELine, DoneELine},
699
700                 {"type",
701                                 {"name",        "classes",      NULL},
702                                 {"",            "",             NULL},
703                                 {DT_CHARPTR,    DT_CHARPTR},
704                                 InitTypes, DoType, DoneClassesAndTypes},
705
706                 {"class",
707                                 {"name",        "commands",     NULL},
708                                 {"",            "",             NULL},
709                                 {DT_CHARPTR,    DT_CHARPTR},
710                                 InitClasses, DoClass, DoneClassesAndTypes},
711
712                 {NULL}
713         };
714
715         include_stack.clear();
716
717         /* Load and parse the config file, if there are any errors then explode */
718
719         /* Make a copy here so if it fails then we can carry on running with an unaffected config */
720         ConfigDataHash newconfig;
721
722         if (this->LoadConf(newconfig, ServerInstance->ConfigFileName, errstr))
723         {
724                 /* If we succeeded, set the ircd config to the new one */
725                 this->config_data = newconfig;
726         }
727         else
728         {
729                 ReportConfigError(errstr.str(), bail, user);
730                 return;
731         }
732
733         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
734         try
735         {
736                 /* Check we dont have more than one of singular tags, or any of them missing
737                  */
738                 for (int Index = 0; Once[Index]; Index++)
739                         if (!CheckOnce(Once[Index], bail, user))
740                                 return;
741
742                 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
743                  */
744                 for (int Index = 0; Values[Index].tag; Index++)
745                 {
746                         char item[MAXBUF];
747                         int dt = Values[Index].datatype;
748                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
749                         dt &= ~DT_ALLOW_NEWLINE;
750
751                         ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
752                         ValueItem vi(item);
753
754                         if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
755                                 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
756
757                         switch (Values[Index].datatype)
758                         {
759                                 case DT_CHARPTR:
760                                 {
761                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
762                                         /* Make sure we also copy the null terminator */
763                                         vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
764                                 }
765                                 break;
766                                 case DT_INTEGER:
767                                 {
768                                         int val = vi.GetInteger();
769                                         ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
770                                         vci->Set(&val, sizeof(int));
771                                 }
772                                 break;
773                                 case DT_BOOLEAN:
774                                 {
775                                         bool val = vi.GetBool();
776                                         ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
777                                         vcb->Set(&val, sizeof(bool));
778                                 }
779                                 break;
780                                 default:
781                                         /* You don't want to know what happens if someones bad code sends us here. */
782                                 break;
783                         }
784
785                         /* We're done with this now */
786                         delete Values[Index].val;
787                 }
788
789                 /* Read the multiple-tag items (class tags, connect tags, etc)
790                  * and call the callbacks associated with them. We have three
791                  * callbacks for these, a 'start', 'item' and 'end' callback.
792                  */
793                 for (int Index = 0; MultiValues[Index].tag; Index++)
794                 {
795                         MultiValues[Index].init_function(this, MultiValues[Index].tag);
796
797                         int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
798
799                         for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
800                         {
801                                 ValueList vl;
802                                 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
803                                 {
804                                         int dt = MultiValues[Index].datatype[valuenum];
805                                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
806                                         dt &= ~DT_ALLOW_NEWLINE;
807
808                                         switch (dt)
809                                         {
810                                                 case DT_CHARPTR:
811                                                 {
812                                                         char item[MAXBUF];
813                                                         if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
814                                                                 vl.push_back(ValueItem(item));
815                                                         else
816                                                                 vl.push_back(ValueItem(""));
817                                                 }
818                                                 break;
819                                                 case DT_INTEGER:
820                                                 {
821                                                         int item = 0;
822                                                         if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
823                                                                 vl.push_back(ValueItem(item));
824                                                         else
825                                                                 vl.push_back(ValueItem(0));
826                                                 }
827                                                 break;
828                                                 case DT_BOOLEAN:
829                                                 {
830                                                         bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
831                                                         vl.push_back(ValueItem(item));
832                                                 }
833                                                 break;
834                                                 default:
835                                                         /* Someone was smoking craq if we got here, and we're all gonna die. */
836                                                 break;
837                                         }
838                                 }
839
840                                 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
841                         }
842
843                         MultiValues[Index].finish_function(this, MultiValues[Index].tag);
844                 }
845
846         }
847
848         catch (CoreException &ce)
849         {
850                 ReportConfigError(ce.GetReason(), bail, user);
851                 return;
852         }
853
854         // write once here, to try it out and make sure its ok
855         ServerInstance->WritePID(this->PID);
856
857         ServerInstance->Log(DEFAULT,"Done reading configuration file.");
858
859         /* If we're rehashing, let's load any new modules, and unload old ones
860          */
861         if (!bail)
862         {
863                 int found_ports = 0;
864                 FailedPortList pl;
865                 ServerInstance->BindPorts(false, found_ports, pl);
866
867                 if (pl.size() && user)
868                 {
869                         user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
870                         user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick);
871                         int j = 1;
872                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
873                         {
874                                 user->WriteServ("NOTICE %s :*** %d.   IP: %s     Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
875                         }
876                 }
877
878                 if (!removed_modules.empty())
879                 {
880                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
881                         {
882                                 if (ServerInstance->UnloadModule(removing->c_str()))
883                                 {
884                                         ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
885
886                                         if (user)
887                                                 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
888
889                                         rem++;
890                                 }
891                                 else
892                                 {
893                                         if (user)
894                                                 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
895                                 }
896                         }
897                 }
898
899                 if (!added_modules.empty())
900                 {
901                         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
902                         {
903                                 if (ServerInstance->LoadModule(adding->c_str()))
904                                 {
905                                         ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
906
907                                         if (user)
908                                                 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
909
910                                         add++;
911                                 }
912                                 else
913                                 {
914                                         if (user)
915                                                 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
916                                 }
917                         }
918                 }
919
920                 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());
921         }
922
923         /** Note: This is safe, the method checks for user == NULL */
924         ServerInstance->Parser->SetupCommandTable(user);
925
926         if (user)
927                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
928         else
929                 ServerInstance->WriteOpers("*** Successfully rehashed server.");
930 }
931
932 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
933 {
934         std::ifstream conf(filename);
935         std::string line;
936         char ch;
937         long linenumber;
938         bool in_tag;
939         bool in_quote;
940         bool in_comment;
941         int character_count = 0;
942
943         linenumber = 1;
944         in_tag = false;
945         in_quote = false;
946         in_comment = false;
947
948         /* Check if the file open failed first */
949         if (!conf)
950         {
951                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
952                 return false;
953         }
954
955         /* Fix the chmod of the file to restrict it to the current user and group */
956         chmod(filename,0600);
957
958         for (unsigned int t = 0; t < include_stack.size(); t++)
959         {
960                 if (std::string(filename) == include_stack[t])
961                 {
962                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
963                         return false;
964                 }
965         }
966
967         /* It's not already included, add it to the list of files we've loaded */
968         include_stack.push_back(filename);
969
970         /* Start reading characters... */
971         while (conf.get(ch))
972         {
973
974                 /*
975                  * Fix for moronic windows issue spotted by Adremelech.
976                  * Some windows editors save text files as utf-16, which is
977                  * a total pain in the ass to parse. Users should save in the
978                  * right config format! If we ever see a file where the first
979                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
980                  * this is most likely a utf-16 file. Bail out and insult user.
981                  */
982                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
983                 {
984                         errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
985                         return false;
986                 }
987
988                 /*
989                  * Here we try and get individual tags on separate lines,
990                  * this would be so easy if we just made people format
991                  * their config files like that, but they don't so...
992                  * We check for a '<' and then know the line is over when
993                  * we get a '>' not inside quotes. If we find two '<' and
994                  * no '>' then die with an error.
995                  */
996
997                 if ((ch == '#') && !in_quote)
998                         in_comment = true;
999
1000                 switch (ch)
1001                 {
1002                         case '\n':
1003                                 if (in_quote)
1004                                         line += '\n';
1005                                 linenumber++;
1006                         case '\r':
1007                                 if (!in_quote)
1008                                         in_comment = false;
1009                         case '\0':
1010                                 continue;
1011                         case '\t':
1012                                 ch = ' ';
1013                 }
1014
1015                 if(in_comment)
1016                         continue;
1017
1018                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1019                  * Note that this WILL NOT usually allow insertion of newlines,
1020                  * because a newline is two characters long. Use it primarily to
1021                  * insert the " symbol.
1022                  *
1023                  * Note that this also involves a further check when parsing the line,
1024                  * which can be found below.
1025                  */
1026                 if ((ch == '\\') && (in_quote) && (in_tag))
1027                 {
1028                         line += ch;
1029                         char real_character;
1030                         if (conf.get(real_character))
1031                         {
1032                                 if (real_character == 'n')
1033                                         real_character = '\n';
1034                                 line += real_character;
1035                                 continue;
1036                         }
1037                         else
1038                         {
1039                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1040                                 return false;
1041                         }
1042                 }
1043
1044                 if (ch != '\r')
1045                         line += ch;
1046
1047                 if (ch == '<')
1048                 {
1049                         if (in_tag)
1050                         {
1051                                 if (!in_quote)
1052                                 {
1053                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1054                                         return false;
1055                                 }
1056                         }
1057                         else
1058                         {
1059                                 if (in_quote)
1060                                 {
1061                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1062                                         return false;
1063                                 }
1064                                 else
1065                                 {
1066                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1067                                         in_tag = true;
1068                                 }
1069                         }
1070                 }
1071                 else if (ch == '"')
1072                 {
1073                         if (in_tag)
1074                         {
1075                                 if (in_quote)
1076                                 {
1077                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1078                                         in_quote = false;
1079                                 }
1080                                 else
1081                                 {
1082                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1083                                         in_quote = true;
1084                                 }
1085                         }
1086                         else
1087                         {
1088                                 if (in_quote)
1089                                 {
1090                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1091                                 }
1092                                 else
1093                                 {
1094                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1095                                 }
1096                         }
1097                 }
1098                 else if (ch == '>')
1099                 {
1100                         if (!in_quote)
1101                         {
1102                                 if (in_tag)
1103                                 {
1104                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
1105                                         in_tag = false;
1106
1107                                         /*
1108                                          * If this finds an <include> then ParseLine can simply call
1109                                          * LoadConf() and load the included config into the same ConfigDataHash
1110                                          */
1111
1112                                         if (!this->ParseLine(target, line, linenumber, errorstream))
1113                                                 return false;
1114
1115                                         line.clear();
1116                                 }
1117                                 else
1118                                 {
1119                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1120                                         return false;
1121                                 }
1122                         }
1123                 }
1124         }
1125
1126         /* 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 */
1127         if (in_comment || in_quote)
1128         {
1129                 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1130                         is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1131         }
1132
1133         return true;
1134 }
1135
1136 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1137 {
1138         return this->LoadConf(target, filename.c_str(), errorstream);
1139 }
1140
1141 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream)
1142 {
1143         std::string tagname;
1144         std::string current_key;
1145         std::string current_value;
1146         KeyValList results;
1147         bool got_name;
1148         bool got_key;
1149         bool in_quote;
1150
1151         got_name = got_key = in_quote = false;
1152
1153         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1154         {
1155                 if (!got_name)
1156                 {
1157                         /* We don't know the tag name yet. */
1158
1159                         if (*c != ' ')
1160                         {
1161                                 if (*c != '<')
1162                                 {
1163                                         tagname += *c;
1164                                 }
1165                         }
1166                         else
1167                         {
1168                                 /* We got to a space, we should have the tagname now. */
1169                                 if(tagname.length())
1170                                 {
1171                                         got_name = true;
1172                                 }
1173                         }
1174                 }
1175                 else
1176                 {
1177                         /* We have the tag name */
1178                         if (!got_key)
1179                         {
1180                                 /* We're still reading the key name */
1181                                 if (*c != '=')
1182                                 {
1183                                         if (*c != ' ')
1184                                         {
1185                                                 current_key += *c;
1186                                         }
1187                                 }
1188                                 else
1189                                 {
1190                                         /* We got an '=', end of the key name. */
1191                                         got_key = true;
1192                                 }
1193                         }
1194                         else
1195                         {
1196                                 /* We have the key name, now we're looking for quotes and the value */
1197
1198                                 /* Correctly handle escaped characters here.
1199                                  * See the XXX'ed section above.
1200                                  */
1201                                 if ((*c == '\\') && (in_quote))
1202                                 {
1203                                         c++;
1204                                         if (*c == 'n')
1205                                                 current_value += '\n';
1206                                         else
1207                                                 current_value += *c;
1208                                         continue;
1209                                 }
1210                                 else if ((*c == '\n') && (in_quote))
1211                                 {
1212                                         /* Got a 'real' \n, treat it as part of the value */
1213                                         current_value += '\n';
1214                                         linenumber++;
1215                                         continue;
1216                                 }
1217                                 else if ((*c == '\r') && (in_quote))
1218                                         /* Got a \r, drop it */
1219                                         continue;
1220
1221                                 if (*c == '"')
1222                                 {
1223                                         if (!in_quote)
1224                                         {
1225                                                 /* We're not already in a quote. */
1226                                                 in_quote = true;
1227                                         }
1228                                         else
1229                                         {
1230                                                 /* Leaving quotes, we have the value */
1231                                                 results.push_back(KeyVal(current_key, current_value));
1232
1233                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1234
1235                                                 in_quote = false;
1236                                                 got_key = false;
1237
1238                                                 if ((tagname == "include") && (current_key == "file"))
1239                                                 {
1240                                                         if (!this->DoInclude(target, current_value, errorstream))
1241                                                                 return false;
1242                                                 }
1243
1244                                                 current_key.clear();
1245                                                 current_value.clear();
1246                                         }
1247                                 }
1248                                 else
1249                                 {
1250                                         if (in_quote)
1251                                         {
1252                                                 current_value += *c;
1253                                         }
1254                                 }
1255                         }
1256                 }
1257         }
1258
1259         /* Finished parsing the tag, add it to the config hash */
1260         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1261
1262         return true;
1263 }
1264
1265 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1266 {
1267         std::string confpath;
1268         std::string newfile;
1269         std::string::size_type pos;
1270
1271         confpath = ServerInstance->ConfigFileName;
1272         newfile = file;
1273
1274         for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1275         {
1276                 if (*c == '\\')
1277                 {
1278                         *c = '/';
1279                 }
1280         }
1281
1282         if (file[0] != '/')
1283         {
1284                 if((pos = confpath.rfind("/")) != std::string::npos)
1285                 {
1286                         /* Leaves us with just the path */
1287                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1288                 }
1289                 else
1290                 {
1291                         errorstream << "Couldn't get config path from: " << confpath << std::endl;
1292                         return false;
1293                 }
1294         }
1295
1296         return LoadConf(target, newfile, errorstream);
1297 }
1298
1299 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1300 {
1301         return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1302 }
1303
1304 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1305 {
1306         std::string value;
1307         bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1308         strlcpy(result, value.c_str(), length);
1309         return r;
1310 }
1311
1312 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1313 {
1314         return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1315 }
1316
1317 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)
1318 {
1319         ConfigDataHash::size_type pos = index;
1320         if((pos >= 0) && (pos < target.count(tag)))
1321         {
1322                 ConfigDataHash::iterator iter = target.find(tag);
1323
1324                 for(int i = 0; i < index; i++)
1325                         iter++;
1326
1327                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1328                 {
1329                         if(j->first == var)
1330                         {
1331                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1332                                 {
1333                                         ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1334                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1335                                                 if (*n == '\n')
1336                                                         *n = ' ';
1337                                 }
1338                                 else
1339                                 {
1340                                         result = j->second;
1341                                         return true;
1342                                 }
1343                         }
1344                 }
1345                 if (!default_value.empty())
1346                 {
1347                         result = default_value;
1348                         return true;
1349                 }
1350         }
1351         else if(pos == 0)
1352         {
1353                 if (!default_value.empty())
1354                 {
1355                         result = default_value;
1356                         return true;
1357                 }
1358         }
1359         return false;
1360 }
1361
1362 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1363 {
1364         return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1365 }
1366
1367 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1368 {
1369         return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1370 }
1371
1372 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1373 {
1374         return ConfValueInteger(target, tag, var, "", index, result);
1375 }
1376
1377 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1378 {
1379         std::string value;
1380         std::istringstream stream;
1381         bool r = ConfValue(target, tag, var, default_value, index, value);
1382         stream.str(value);
1383         if(!(stream >> result))
1384                 return false;
1385         else
1386         {
1387                 if (!value.empty())
1388                 {
1389                         if (value.substr(0,2) == "0x")
1390                         {
1391                                 char* endptr;
1392
1393                                 value.erase(0,2);
1394                                 result = strtol(value.c_str(), &endptr, 16);
1395
1396                                 /* No digits found */
1397                                 if (endptr == value.c_str())
1398                                         return false;
1399                         }
1400                         else
1401                         {
1402                                 char denominator = *(value.end() - 1);
1403                                 switch (toupper(denominator))
1404                                 {
1405                                         case 'K':
1406                                                 /* Kilobytes -> bytes */
1407                                                 result = result * 1024;
1408                                         break;
1409                                         case 'M':
1410                                                 /* Megabytes -> bytes */
1411                                                 result = result * 1024 * 1024;
1412                                         break;
1413                                         case 'G':
1414                                                 /* Gigabytes -> bytes */
1415                                                 result = result * 1024 * 1024 * 1024;
1416                                         break;
1417                                 }
1418                         }
1419                 }
1420         }
1421         return r;
1422 }
1423
1424
1425 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1426 {
1427         return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1428 }
1429
1430 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1431 {
1432         return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1433 }
1434
1435 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1436 {
1437         return ConfValueBool(target, tag, var, "", index);
1438 }
1439
1440 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1441 {
1442         std::string result;
1443         if(!ConfValue(target, tag, var, default_value, index, result))
1444                 return false;
1445
1446         return ((result == "yes") || (result == "true") || (result == "1"));
1447 }
1448
1449 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1450 {
1451         return target.count(tag);
1452 }
1453
1454 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1455 {
1456         return target.count(tag);
1457 }
1458
1459 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1460 {
1461         return ConfVarEnum(target, std::string(tag), index);
1462 }
1463
1464 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1465 {
1466         ConfigDataHash::size_type pos = index;
1467
1468         if((pos >= 0) && (pos < target.count(tag)))
1469         {
1470                 ConfigDataHash::const_iterator iter = target.find(tag);
1471
1472                 for(int i = 0; i < index; i++)
1473                         iter++;
1474
1475                 return iter->second.size();
1476         }
1477
1478         return 0;
1479 }
1480
1481 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1482  */
1483 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1484 {
1485         if (!fname || !*fname)
1486                 return false;
1487
1488         FILE* file = NULL;
1489         char linebuf[MAXBUF];
1490
1491         F.clear();
1492
1493         if ((*fname != '/') && (*fname != '\\'))
1494         {
1495                 std::string::size_type pos;
1496                 std::string confpath = ServerInstance->ConfigFileName;
1497                 std::string newfile = fname;
1498
1499                 if ((pos = confpath.rfind("/")) != std::string::npos)
1500                         newfile = confpath.substr(0, pos) + std::string("/") + fname;
1501                 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1502                         newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1503
1504                 if (!FileExists(newfile.c_str()))
1505                         return false;
1506                 file =  fopen(newfile.c_str(), "r");
1507         }
1508         else
1509         {
1510                 if (!FileExists(fname))
1511                         return false;
1512                 file =  fopen(fname, "r");
1513         }
1514
1515         if (file)
1516         {
1517                 while (!feof(file))
1518                 {
1519                         if (fgets(linebuf, sizeof(linebuf), file))
1520                                 linebuf[strlen(linebuf)-1] = 0;
1521                         else
1522                                 *linebuf = 0;
1523
1524                         if (!feof(file))
1525                         {
1526                                 F.push_back(*linebuf ? linebuf : " ");
1527                         }
1528                 }
1529
1530                 fclose(file);
1531         }
1532         else
1533                 return false;
1534
1535         return true;
1536 }
1537
1538 bool ServerConfig::FileExists(const char* file)
1539 {
1540         struct stat sb;
1541         if (stat(file, &sb) == -1)
1542                 return false;
1543
1544         if ((sb.st_mode & S_IFDIR) > 0)
1545                 return false;
1546              
1547         FILE *input;
1548         if ((input = fopen (file, "r")) == NULL)
1549                 return false;
1550         else
1551         {
1552                 fclose(input);
1553                 return true;
1554         }
1555 }
1556
1557 char* ServerConfig::CleanFilename(char* name)
1558 {
1559         char* p = name + strlen(name);
1560         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1561         return (p != name ? ++p : p);
1562 }
1563
1564
1565 bool ServerConfig::DirValid(const char* dirandfile)
1566 {
1567 #ifdef WINDOWS
1568         return true;
1569 #endif
1570
1571         char work[1024];
1572         char buffer[1024];
1573         char otherdir[1024];
1574         int p;
1575
1576         strlcpy(work, dirandfile, 1024);
1577         p = strlen(work);
1578
1579         // we just want the dir
1580         while (*work)
1581         {
1582                 if (work[p] == '/')
1583                 {
1584                         work[p] = '\0';
1585                         break;
1586                 }
1587
1588                 work[p--] = '\0';
1589         }
1590
1591         // Get the current working directory
1592         if (getcwd(buffer, 1024 ) == NULL )
1593                 return false;
1594
1595         if (chdir(work) == -1)
1596                 return false;
1597
1598         if (getcwd(otherdir, 1024 ) == NULL )
1599                 return false;
1600
1601         if (chdir(buffer) == -1)
1602                 return false;
1603
1604         size_t t = strlen(work);
1605
1606         if (strlen(otherdir) >= t)
1607         {
1608                 otherdir[t] = '\0';
1609                 if (!strcmp(otherdir,work))
1610                 {
1611                         return true;
1612                 }
1613
1614                 return false;
1615         }
1616         else
1617         {
1618                 return false;
1619         }
1620 }
1621
1622 std::string ServerConfig::GetFullProgDir()
1623 {
1624         char buffer[PATH_MAX+1];
1625 #ifdef WINDOWS
1626         /* Windows has specific api calls to get the exe path that never fail.
1627          * For once, windows has something of use, compared to the POSIX code
1628          * for this, this is positively neato.
1629          */
1630         if (GetModuleFileName(NULL, buffer, MAX_PATH))
1631         {
1632                 std::string fullpath = buffer;
1633                 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1634                 return std::string(fullpath, 0, n);
1635         }
1636 #else
1637         // Get the current working directory
1638         if (getcwd(buffer, PATH_MAX))
1639         {
1640                 std::string remainder = this->argv[0];
1641
1642                 /* Does argv[0] start with /? its a full path, use it */
1643                 if (remainder[0] == '/')
1644                 {
1645                         std::string::size_type n = remainder.rfind("/inspircd");
1646                         return std::string(remainder, 0, n);
1647                 }
1648
1649                 std::string fullpath = std::string(buffer) + "/" + remainder;
1650                 std::string::size_type n = fullpath.rfind("/inspircd");
1651                 return std::string(fullpath, 0, n);
1652         }
1653 #endif
1654         return "/";
1655 }
1656
1657 InspIRCd* ServerConfig::GetInstance()
1658 {
1659         return ServerInstance;
1660 }
1661
1662
1663 ValueItem::ValueItem(int value)
1664 {
1665         std::stringstream n;
1666         n << value;
1667         v = n.str();
1668 }
1669
1670 ValueItem::ValueItem(bool value)
1671 {
1672         std::stringstream n;
1673         n << value;
1674         v = n.str();
1675 }
1676
1677 ValueItem::ValueItem(char* value)
1678 {
1679         v = value;
1680 }
1681
1682 void ValueItem::Set(char* value)
1683 {
1684         v = value;
1685 }
1686
1687 void ValueItem::Set(const char* value)
1688 {
1689         v = value;
1690 }
1691
1692 void ValueItem::Set(int value)
1693 {
1694         std::stringstream n;
1695         n << value;
1696         v = n.str();
1697 }
1698
1699 int ValueItem::GetInteger()
1700 {
1701         if (v.empty())
1702                 return 0;
1703         return atoi(v.c_str());
1704 }
1705
1706 char* ValueItem::GetString()
1707 {
1708         return (char*)v.c_str();
1709 }
1710
1711 bool ValueItem::GetBool()
1712 {
1713         return (GetInteger() || v == "yes" || v == "true");
1714 }
1715