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