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