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