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