]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
46bb9231ea8e55e8f6c81b63134c2a764071509d
[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         if (user)
924                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
925         else
926                 ServerInstance->WriteOpers("*** Successfully rehashed server.");
927 }
928
929 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
930 {
931         std::ifstream conf(filename);
932         std::string line;
933         char ch;
934         long linenumber;
935         bool in_tag;
936         bool in_quote;
937         bool in_comment;
938         int character_count = 0;
939
940         linenumber = 1;
941         in_tag = false;
942         in_quote = false;
943         in_comment = false;
944
945         /* Check if the file open failed first */
946         if (!conf)
947         {
948                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
949                 return false;
950         }
951
952         /* Fix the chmod of the file to restrict it to the current user and group */
953         chmod(filename,0600);
954
955         for (unsigned int t = 0; t < include_stack.size(); t++)
956         {
957                 if (std::string(filename) == include_stack[t])
958                 {
959                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
960                         return false;
961                 }
962         }
963
964         /* It's not already included, add it to the list of files we've loaded */
965         include_stack.push_back(filename);
966
967         /* Start reading characters... */
968         while(conf.get(ch))
969         {
970
971                 /*
972                  * Fix for moronic windows issue spotted by Adremelech.
973                  * Some windows editors save text files as utf-16, which is
974                  * a total pain in the ass to parse. Users should save in the
975                  * right config format! If we ever see a file where the first
976                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
977                  * this is most likely a utf-16 file. Bail out and insult user.
978                  */
979                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
980                 {
981                         errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
982                         return false;
983                 }
984
985                 /*
986                  * Here we try and get individual tags on separate lines,
987                  * this would be so easy if we just made people format
988                  * their config files like that, but they don't so...
989                  * We check for a '<' and then know the line is over when
990                  * we get a '>' not inside quotes. If we find two '<' and
991                  * no '>' then die with an error.
992                  */
993
994                 if((ch == '#') && !in_quote)
995                         in_comment = true;
996
997                 switch(ch)
998                 {
999                         case '\n':
1000                                 if (in_quote)
1001                                         line += '\n';
1002                                 linenumber++;
1003                         case '\r':
1004                                 if (!in_quote)
1005                                         in_comment = false;
1006                         case '\0':
1007                                 continue;
1008                         case '\t':
1009                                 ch = ' ';
1010                 }
1011
1012                 if(in_comment)
1013                         continue;
1014
1015                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1016                  * Note that this WILL NOT usually allow insertion of newlines,
1017                  * because a newline is two characters long. Use it primarily to
1018                  * insert the " symbol.
1019                  *
1020                  * Note that this also involves a further check when parsing the line,
1021                  * which can be found below.
1022                  */
1023                 if ((ch == '\\') && (in_quote) && (in_tag))
1024                 {
1025                         line += ch;
1026                         char real_character;
1027                         if (conf.get(real_character))
1028                         {
1029                                 if (real_character == 'n')
1030                                         real_character = '\n';
1031                                 line += real_character;
1032                                 continue;
1033                         }
1034                         else
1035                         {
1036                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1037                                 return false;
1038                         }
1039                 }
1040
1041                 if (ch != '\r')
1042                         line += ch;
1043
1044                 if(ch == '<')
1045                 {
1046                         if(in_tag)
1047                         {
1048                                 if(!in_quote)
1049                                 {
1050                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1051                                         return false;
1052                                 }
1053                         }
1054                         else
1055                         {
1056                                 if(in_quote)
1057                                 {
1058                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1059                                         return false;
1060                                 }
1061                                 else
1062                                 {
1063                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1064                                         in_tag = true;
1065                                 }
1066                         }
1067                 }
1068                 else if(ch == '"')
1069                 {
1070                         if(in_tag)
1071                         {
1072                                 if(in_quote)
1073                                 {
1074                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1075                                         in_quote = false;
1076                                 }
1077                                 else
1078                                 {
1079                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1080                                         in_quote = true;
1081                                 }
1082                         }
1083                         else
1084                         {
1085                                 if(in_quote)
1086                                 {
1087                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1088                                 }
1089                                 else
1090                                 {
1091                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1092                                 }
1093                         }
1094                 }
1095                 else if(ch == '>')
1096                 {
1097                         if(!in_quote)
1098                         {
1099                                 if(in_tag)
1100                                 {
1101                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
1102                                         in_tag = false;
1103
1104                                         /*
1105                                          * If this finds an <include> then ParseLine can simply call
1106                                          * LoadConf() and load the included config into the same ConfigDataHash
1107                                          */
1108
1109                                         if(!this->ParseLine(target, line, linenumber, errorstream))
1110                                                 return false;
1111
1112                                         line.clear();
1113                                 }
1114                                 else
1115                                 {
1116                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1117                                         return false;
1118                                 }
1119                         }
1120                 }
1121         }
1122
1123         return true;
1124 }
1125
1126 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1127 {
1128         return this->LoadConf(target, filename.c_str(), errorstream);
1129 }
1130
1131 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1132 {
1133         std::string tagname;
1134         std::string current_key;
1135         std::string current_value;
1136         KeyValList results;
1137         bool got_name;
1138         bool got_key;
1139         bool in_quote;
1140
1141         got_name = got_key = in_quote = false;
1142
1143         //std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1144
1145         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1146         {
1147                 if(!got_name)
1148                 {
1149                         /* We don't know the tag name yet. */
1150
1151                         if(*c != ' ')
1152                         {
1153                                 if(*c != '<')
1154                                 {
1155                                         tagname += *c;
1156                                 }
1157                         }
1158                         else
1159                         {
1160                                 /* We got to a space, we should have the tagname now. */
1161                                 if(tagname.length())
1162                                 {
1163                                         got_name = true;
1164                                 }
1165                         }
1166                 }
1167                 else
1168                 {
1169                         /* We have the tag name */
1170                         if (!got_key)
1171                         {
1172                                 /* We're still reading the key name */
1173                                 if (*c != '=')
1174                                 {
1175                                         if (*c != ' ')
1176                                         {
1177                                                 current_key += *c;
1178                                         }
1179                                 }
1180                                 else
1181                                 {
1182                                         /* We got an '=', end of the key name. */
1183                                         got_key = true;
1184                                 }
1185                         }
1186                         else
1187                         {
1188                                 /* We have the key name, now we're looking for quotes and the value */
1189
1190                                 /* Correctly handle escaped characters here.
1191                                  * See the XXX'ed section above.
1192                                  */
1193                                 if ((*c == '\\') && (in_quote))
1194                                 {
1195                                         c++;
1196                                         if (*c == 'n')
1197                                                 current_value += '\n';
1198                                         else
1199                                                 current_value += *c;
1200                                         continue;
1201                                 }
1202                                 else if ((*c == '\n') && (in_quote))
1203                                 {
1204                                         /* Got a 'real' \n, treat it as part of the value */
1205                                         current_value += '\n';
1206                                         continue;
1207                                 }
1208                                 else if ((*c == '\r') && (in_quote))
1209                                         /* Got a \r, drop it */
1210                                         continue;
1211
1212                                 if (*c == '"')
1213                                 {
1214                                         if (!in_quote)
1215                                         {
1216                                                 /* We're not already in a quote. */
1217                                                 in_quote = true;
1218                                         }
1219                                         else
1220                                         {
1221                                                 /* Leaving quotes, we have the value */
1222                                                 results.push_back(KeyVal(current_key, current_value));
1223
1224                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1225
1226                                                 in_quote = false;
1227                                                 got_key = false;
1228
1229                                                 if((tagname == "include") && (current_key == "file"))
1230                                                 {
1231                                                         if(!this->DoInclude(target, current_value, errorstream))
1232                                                                 return false;
1233                                                 }
1234
1235                                                 current_key.clear();
1236                                                 current_value.clear();
1237                                         }
1238                                 }
1239                                 else
1240                                 {
1241                                         if(in_quote)
1242                                         {
1243                                                 current_value += *c;
1244                                         }
1245                                 }
1246                         }
1247                 }
1248         }
1249
1250         /* Finished parsing the tag, add it to the config hash */
1251         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1252
1253         return true;
1254 }
1255
1256 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1257 {
1258         std::string confpath;
1259         std::string newfile;
1260         std::string::size_type pos;
1261
1262         confpath = ServerInstance->ConfigFileName;
1263         newfile = file;
1264
1265         for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1266         {
1267                 if (*c == '\\')
1268                 {
1269                         *c = '/';
1270                 }
1271         }
1272
1273         if (file[0] != '/')
1274         {
1275                 if((pos = confpath.rfind("/")) != std::string::npos)
1276                 {
1277                         /* Leaves us with just the path */
1278                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1279                 }
1280                 else
1281                 {
1282                         errorstream << "Couldn't get config path from: " << confpath << std::endl;
1283                         return false;
1284                 }
1285         }
1286
1287         return LoadConf(target, newfile, errorstream);
1288 }
1289
1290 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1291 {
1292         return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1293 }
1294
1295 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1296 {
1297         std::string value;
1298         bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1299         strlcpy(result, value.c_str(), length);
1300         return r;
1301 }
1302
1303 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1304 {
1305         return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1306 }
1307
1308 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)
1309 {
1310         ConfigDataHash::size_type pos = index;
1311         if((pos >= 0) && (pos < target.count(tag)))
1312         {
1313                 ConfigDataHash::iterator iter = target.find(tag);
1314
1315                 for(int i = 0; i < index; i++)
1316                         iter++;
1317
1318                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1319                 {
1320                         if(j->first == var)
1321                         {
1322                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1323                                 {
1324                                         ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1325                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1326                                                 if (*n == '\n')
1327                                                         *n = ' ';
1328                                 }
1329                                 else
1330                                 {
1331                                         result = j->second;
1332                                         return true;
1333                                 }
1334                         }
1335                 }
1336                 if (!default_value.empty())
1337                 {
1338                         result = default_value;
1339                         return true;
1340                 }
1341         }
1342         else if(pos == 0)
1343         {
1344                 if (!default_value.empty())
1345                 {
1346                         result = default_value;
1347                         return true;
1348                 }
1349         }
1350         return false;
1351 }
1352
1353 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1354 {
1355         return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1356 }
1357
1358 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1359 {
1360         return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1361 }
1362
1363 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1364 {
1365         return ConfValueInteger(target, tag, var, "", index, result);
1366 }
1367
1368 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1369 {
1370         std::string value;
1371         std::istringstream stream;
1372         bool r = ConfValue(target, tag, var, default_value, index, value);
1373         stream.str(value);
1374         if(!(stream >> result))
1375                 return false;
1376         else
1377         {
1378                 if (!value.empty())
1379                 {
1380                         if (value.substr(0,2) == "0x")
1381                         {
1382                                 char* endptr;
1383
1384                                 value.erase(0,2);
1385                                 result = strtol(value.c_str(), &endptr, 16);
1386
1387                                 /* No digits found */
1388                                 if (endptr == value.c_str())
1389                                         return false;
1390                         }
1391                         else
1392                         {
1393                                 char denominator = *(value.end() - 1);
1394                                 switch (toupper(denominator))
1395                                 {
1396                                         case 'K':
1397                                                 /* Kilobytes -> bytes */
1398                                                 result = result * 1024;
1399                                         break;
1400                                         case 'M':
1401                                                 /* Megabytes -> bytes */
1402                                                 result = result * 1024 * 1024;
1403                                         break;
1404                                         case 'G':
1405                                                 /* Gigabytes -> bytes */
1406                                                 result = result * 1024 * 1024 * 1024;
1407                                         break;
1408                                 }
1409                         }
1410                 }
1411         }
1412         return r;
1413 }
1414
1415
1416 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1417 {
1418         return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1419 }
1420
1421 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1422 {
1423         return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1424 }
1425
1426 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1427 {
1428         return ConfValueBool(target, tag, var, "", index);
1429 }
1430
1431 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1432 {
1433         std::string result;
1434         if(!ConfValue(target, tag, var, default_value, index, result))
1435                 return false;
1436
1437         return ((result == "yes") || (result == "true") || (result == "1"));
1438 }
1439
1440 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1441 {
1442         return target.count(tag);
1443 }
1444
1445 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1446 {
1447         return target.count(tag);
1448 }
1449
1450 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1451 {
1452         return ConfVarEnum(target, std::string(tag), index);
1453 }
1454
1455 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1456 {
1457         ConfigDataHash::size_type pos = index;
1458
1459         if((pos >= 0) && (pos < target.count(tag)))
1460         {
1461                 ConfigDataHash::const_iterator iter = target.find(tag);
1462
1463                 for(int i = 0; i < index; i++)
1464                         iter++;
1465
1466                 return iter->second.size();
1467         }
1468
1469         return 0;
1470 }
1471
1472 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1473  */
1474 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1475 {
1476         if (!fname || !*fname)
1477                 return false;
1478
1479         FILE* file = NULL;
1480         char linebuf[MAXBUF];
1481
1482         F.clear();
1483
1484         if ((*fname != '/') && (*fname != '\\'))
1485         {
1486                 std::string::size_type pos;
1487                 std::string confpath = ServerInstance->ConfigFileName;
1488                 std::string newfile = fname;
1489
1490                 if ((pos = confpath.rfind("/")) != std::string::npos)
1491                         newfile = confpath.substr(0, pos) + std::string("/") + fname;
1492                 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1493                         newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1494
1495                 if (!FileExists(newfile.c_str()))
1496                         return false;
1497                 file =  fopen(newfile.c_str(), "r");
1498         }
1499         else
1500         {
1501                 if (!FileExists(fname))
1502                         return false;
1503                 file =  fopen(fname, "r");
1504         }
1505
1506         if (file)
1507         {
1508                 while (!feof(file))
1509                 {
1510                         if (fgets(linebuf, sizeof(linebuf), file))
1511                                 linebuf[strlen(linebuf)-1] = 0;
1512                         else
1513                                 *linebuf = 0;
1514
1515                         if (!feof(file))
1516                         {
1517                                 F.push_back(*linebuf ? linebuf : " ");
1518                         }
1519                 }
1520
1521                 fclose(file);
1522         }
1523         else
1524                 return false;
1525
1526         return true;
1527 }
1528
1529 bool ServerConfig::FileExists(const char* file)
1530 {
1531         struct stat sb;
1532         if (stat(file, &sb) == -1)
1533                 return false;
1534
1535         if ((sb.st_mode & S_IFDIR) > 0)
1536                 return false;
1537              
1538         FILE *input;
1539         if ((input = fopen (file, "r")) == NULL)
1540                 return false;
1541         else
1542         {
1543                 fclose(input);
1544                 return true;
1545         }
1546 }
1547
1548 char* ServerConfig::CleanFilename(char* name)
1549 {
1550         char* p = name + strlen(name);
1551         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1552         return (p != name ? ++p : p);
1553 }
1554
1555
1556 bool ServerConfig::DirValid(const char* dirandfile)
1557 {
1558 #ifdef WINDOWS
1559         return true;
1560 #endif
1561
1562         char work[1024];
1563         char buffer[1024];
1564         char otherdir[1024];
1565         int p;
1566
1567         strlcpy(work, dirandfile, 1024);
1568         p = strlen(work);
1569
1570         // we just want the dir
1571         while (*work)
1572         {
1573                 if (work[p] == '/')
1574                 {
1575                         work[p] = '\0';
1576                         break;
1577                 }
1578
1579                 work[p--] = '\0';
1580         }
1581
1582         // Get the current working directory
1583         if (getcwd(buffer, 1024 ) == NULL )
1584                 return false;
1585
1586         if (chdir(work) == -1)
1587                 return false;
1588
1589         if (getcwd(otherdir, 1024 ) == NULL )
1590                 return false;
1591
1592         if (chdir(buffer) == -1)
1593                 return false;
1594
1595         size_t t = strlen(work);
1596
1597         if (strlen(otherdir) >= t)
1598         {
1599                 otherdir[t] = '\0';
1600                 if (!strcmp(otherdir,work))
1601                 {
1602                         return true;
1603                 }
1604
1605                 return false;
1606         }
1607         else
1608         {
1609                 return false;
1610         }
1611 }
1612
1613 std::string ServerConfig::GetFullProgDir()
1614 {
1615         char buffer[PATH_MAX+1];
1616 #ifdef WINDOWS
1617         /* Windows has specific api calls to get the exe path that never fail.
1618          * For once, windows has something of use, compared to the POSIX code
1619          * for this, this is positively neato.
1620          */
1621         if (GetModuleFileName(NULL, buffer, MAX_PATH))
1622         {
1623                 std::string fullpath = buffer;
1624                 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1625                 return std::string(fullpath, 0, n);
1626         }
1627 #else
1628         // Get the current working directory
1629         if (getcwd(buffer, PATH_MAX))
1630         {
1631                 std::string remainder = this->argv[0];
1632
1633                 /* Does argv[0] start with /? its a full path, use it */
1634                 if (remainder[0] == '/')
1635                 {
1636                         std::string::size_type n = remainder.rfind("/inspircd");
1637                         return std::string(remainder, 0, n);
1638                 }
1639
1640                 std::string fullpath = std::string(buffer) + "/" + remainder;
1641                 std::string::size_type n = fullpath.rfind("/inspircd");
1642                 return std::string(fullpath, 0, n);
1643         }
1644 #endif
1645         return "/";
1646 }
1647
1648 InspIRCd* ServerConfig::GetInstance()
1649 {
1650         return ServerInstance;
1651 }
1652
1653
1654 ValueItem::ValueItem(int value)
1655 {
1656         std::stringstream n;
1657         n << value;
1658         v = n.str();
1659 }
1660
1661 ValueItem::ValueItem(bool value)
1662 {
1663         std::stringstream n;
1664         n << value;
1665         v = n.str();
1666 }
1667
1668 ValueItem::ValueItem(char* value)
1669 {
1670         v = value;
1671 }
1672
1673 void ValueItem::Set(char* value)
1674 {
1675         v = value;
1676 }
1677
1678 void ValueItem::Set(const char* value)
1679 {
1680         v = value;
1681 }
1682
1683 void ValueItem::Set(int value)
1684 {
1685         std::stringstream n;
1686         n << value;
1687         v = n.str();
1688 }
1689
1690 int ValueItem::GetInteger()
1691 {
1692         if (v.empty())
1693                 return 0;
1694         return atoi(v.c_str());
1695 }
1696
1697 char* ValueItem::GetString()
1698 {
1699         return (char*)v.c_str();
1700 }
1701
1702 bool ValueItem::GetBool()
1703 {
1704         return (GetInteger() || v == "yes" || v == "true");
1705 }
1706