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