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