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