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