]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Fix valgrind issues and crashes on exit
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15 /* $CopyInstall: conf/inspircd.quotes.example $(CONPATH) */
16 /* $CopyInstall: conf/inspircd.rules.example $(CONPATH) */
17 /* $CopyInstall: conf/inspircd.motd.example $(CONPATH) */
18 /* $CopyInstall: conf/inspircd.helpop-full.example $(CONPATH) */
19 /* $CopyInstall: conf/inspircd.helpop.example $(CONPATH) */
20 /* $CopyInstall: conf/inspircd.censor.example $(CONPATH) */
21 /* $CopyInstall: conf/inspircd.filter.example $(CONPATH) */
22 /* $CopyInstall: conf/inspircd.conf.example $(CONPATH) */
23 /* $CopyInstall: conf/modules.conf.example $(CONPATH) */
24 /* $CopyInstall: conf/opers.conf.example $(CONPATH) */
25 /* $CopyInstall: conf/links.conf.example $(CONPATH) */
26 /* $CopyInstall: .gdbargs $(BASE) */
27
28 #include "inspircd.h"
29 #include <fstream>
30 #include "xline.h"
31 #include "exitcodes.h"
32 #include "commands/cmd_whowas.h"
33 #include "modes/cmode_h.h"
34
35 ServerConfig::ServerConfig()
36 {
37         *sid = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
38         *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
39         *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
40         *UserStats = *DisabledCommands = *SuffixQuit = '\0';
41         WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
42         log_file = NULL;
43         NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
44         CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
45         dns_timeout = DieDelay = 5;
46         MaxTargets = 20;
47         NetBufferSize = 10240;
48         SoftLimit = ServerInstance->SE->GetMaxFds();
49         MaxConn = SOMAXCONN;
50         MaxWhoResults = 0;
51         debugging = 0;
52         MaxChans = 20;
53         OperMaxChans = 30;
54         c_ipv4_range = 32;
55         c_ipv6_range = 128;
56 }
57
58 void ServerConfig::Update005()
59 {
60         std::stringstream out(data005);
61         std::string token;
62         std::string line5;
63         int token_counter = 0;
64         isupport.clear();
65         while (out >> token)
66         {
67                 line5 = line5 + token + " ";
68                 token_counter++;
69                 if (token_counter >= 13)
70                 {
71                         char buf[MAXBUF];
72                         snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
73                         isupport.push_back(buf);
74                         line5.clear();
75                         token_counter = 0;
76                 }
77         }
78         if (!line5.empty())
79         {
80                 char buf[MAXBUF];
81                 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
82                 isupport.push_back(buf);
83         }
84 }
85
86 void ServerConfig::Send005(User* user)
87 {
88         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
89                 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
90 }
91
92 bool ServerConfig::CheckOnce(const char* tag)
93 {
94         int count = ConfValueEnum(tag);
95
96         if (count > 1)
97                 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
98         if (count < 1)
99                 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
100         return true;
101 }
102
103 static void ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
104 {
105         for (const char* ptr = p; *ptr; ++ptr)
106         {
107                 if (*ptr == ' ')
108                         throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
109         }
110 }
111
112 /* NOTE: Before anyone asks why we're not using inet_pton for this, it is because inet_pton and friends do not return so much detail,
113  * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
114  * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
115  */
116 static void ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
117 {
118         int num_dots = 0;
119         int num_seps = 0;
120         int not_numbers = false;
121         int not_hex = false;
122
123         if (*p)
124         {
125                 if (*p == '.')
126                         throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
127
128                 for (const char* ptr = p; *ptr; ++ptr)
129                 {
130                         if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
131                                 continue;
132
133                         if (*ptr != ':' && *ptr != '.')
134                         {
135                                 if (*ptr < '0' || *ptr > '9')
136                                         not_numbers = true;
137                                 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
138                                         not_hex = true;
139                         }
140                         switch (*ptr)
141                         {
142                                 case ' ':
143                                         throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
144                                 case '.':
145                                         num_dots++;
146                                 break;
147                                 case ':':
148                                         num_seps++;
149                                 break;
150                         }
151                 }
152
153                 if (num_dots > 3)
154                         throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
155
156                 if (num_seps > 8)
157                         throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
158
159                 if (num_seps == 0 && num_dots < 3 && !wild)
160                         throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
161
162                 if (num_seps == 0 && num_dots == 3 && not_numbers)
163                         throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
164
165                 if (num_seps != 0 && not_hex)
166                         throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
167
168                 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
169                         throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
170         }
171 }
172
173 static void ValidateHostname(const char* p, const std::string &tag, const std::string &val)
174 {
175         int num_dots = 0;
176         if (*p)
177         {
178                 if (*p == '.')
179                         throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
180                 for (const char* ptr = p; *ptr; ++ptr)
181                 {
182                         switch (*ptr)
183                         {
184                                 case ' ':
185                                         throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
186                                 case '.':
187                                         num_dots++;
188                                 break;
189                         }
190                 }
191                 if (num_dots == 0)
192                         throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
193         }
194 }
195
196 // Specialized validators
197
198 static bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
199 {
200         if ((data.GetInteger() < 1) || (data.GetInteger() > 31))
201         {
202                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <security:maxtargets> value is greater than 31 or less than 1, set to 20.");
203                 data.Set(20);
204         }
205         return true;
206 }
207
208 static bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
209 {
210         if ((data.GetInteger() < 1) || (data.GetInteger() > ServerInstance->SE->GetMaxFds()))
211         {
212                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:softlimit> value is greater than %d or less than 0, set to %d.",ServerInstance->SE->GetMaxFds(),ServerInstance->SE->GetMaxFds());
213                 data.Set(ServerInstance->SE->GetMaxFds());
214         }
215         return true;
216 }
217
218 static bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
219 {
220         if (data.GetInteger() > SOMAXCONN)
221                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
222         return true;
223 }
224
225 bool ServerConfig::ApplyDisabledCommands(const char* data)
226 {
227         std::stringstream dcmds(data);
228         std::string thiscmd;
229
230         /* Enable everything first */
231         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
232                 x->second->Disable(false);
233
234         /* Now disable all the ones which the user wants disabled */
235         while (dcmds >> thiscmd)
236         {
237                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
238                 if (cm != ServerInstance->Parser->cmdlist.end())
239                 {
240                         cm->second->Disable(true);
241                 }
242         }
243         return true;
244 }
245
246 static bool ValidateDisabledUModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
247 {
248         memset(conf->DisabledUModes, 0, sizeof(conf->DisabledUModes));
249         for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
250         {
251                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
252                 conf->DisabledUModes[*p - 'A'] = 1;
253         }
254         return true;
255 }
256
257 static bool ValidateDisabledCModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
258 {
259         memset(conf->DisabledCModes, 0, sizeof(conf->DisabledCModes));
260         for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
261         {
262                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
263                 conf->DisabledCModes[*p - 'A'] = 1;
264         }
265         return true;
266 }
267
268 #ifdef WINDOWS
269 // Note: the windows validator is in win32wrapper.cpp
270 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data);
271 #else
272 static bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
273 {
274         if (!*(data.GetString()))
275         {
276                 std::string nameserver;
277                 // attempt to look up their nameserver from /etc/resolv.conf
278                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
279                 std::ifstream resolv("/etc/resolv.conf");
280                 bool found_server = false;
281
282                 if (resolv.is_open())
283                 {
284                         while (resolv >> nameserver)
285                         {
286                                 if ((nameserver == "nameserver") && (!found_server))
287                                 {
288                                         resolv >> nameserver;
289                                         data.Set(nameserver.c_str());
290                                         found_server = true;
291                                         ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
292                                 }
293                         }
294
295                         if (!found_server)
296                         {
297                                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
298                                 data.Set("127.0.0.1");
299                         }
300                 }
301                 else
302                 {
303                         ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
304                         data.Set("127.0.0.1");
305                 }
306         }
307         return true;
308 }
309 #endif
310
311 static bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
312 {
313         ServerInstance->Logs->Log("CONFIG",DEFAULT,"Validating server name");
314         /* If we already have a servername, and they changed it, we should throw an exception. */
315         if (!strchr(data.GetString(), '.'))
316         {
317                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s.'",
318                         data.GetString(),data.GetString());
319                 std::string moo = data.GetValue();
320                 data.Set(moo.append("."));
321         }
322         ValidateHostname(data.GetString(), "server", "name");
323         return true;
324 }
325
326 static bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
327 {
328         // 65534 not 65535 because of null terminator
329         if ((!data.GetInteger()) || (data.GetInteger() > 65534) || (data.GetInteger() < 1024))
330         {
331                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
332                 data.Set(10240);
333         }
334         return true;
335 }
336
337 static bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
338 {
339         if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
340         {
341                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 1024.");
342                 data.Set(1024);
343         }
344         return true;
345 }
346
347 static bool ValidateHalfOp(ServerConfig* conf, const char*, const char*, ValueItem &data)
348 {
349         ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
350         if (data.GetBool() && !mh) {
351                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
352                 mh = new ModeChannelHalfOp;
353                 ServerInstance->Modes->AddMode(mh);
354         } else if (!data.GetBool() && mh) {
355                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
356                 ServerInstance->Modes->DelMode(mh);
357                 delete mh;
358         }
359         return true;
360 }
361
362 static bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
363 {
364         conf->ReadFile(conf->MOTD, data.GetString());
365         return true;
366 }
367
368 static bool ValidateNotEmpty(ServerConfig*, const char* tag, const char* val, ValueItem &data)
369 {
370         if (data.GetValue().empty())
371                 throw CoreException(std::string("The value for <")+tag+":"+val+"> cannot be empty!");
372         return true;
373 }
374
375 static bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
376 {
377         conf->ReadFile(conf->RULES, data.GetString());
378         return true;
379 }
380
381 static bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
382 {
383         memset(conf->HideModeLists, 0, sizeof(conf->HideModeLists));
384         for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
385                 conf->HideModeLists[*x] = true;
386         return true;
387 }
388
389 static bool ValidateExemptChanOps(ServerConfig* conf, const char*, const char*, ValueItem &data)
390 {
391         memset(conf->ExemptChanOps, 0, sizeof(conf->ExemptChanOps));
392         for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
393                 conf->ExemptChanOps[*x] = true;
394         return true;
395 }
396
397 static bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
398 {
399         const std::string& v = data.GetValue();
400
401         if (v == "ops")
402                 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
403         else if (v == "all")
404                 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
405         else if (v == "dynamic")
406                 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
407         else
408                 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
409
410         return true;
411 }
412
413 static bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
414 {
415         ServerInstance->Logs->Log("CONFIG",DEFAULT,"Validating server id");
416
417         const char *sid = data.GetString();
418
419         if (*sid && !ServerInstance->IsSID(sid))
420         {
421                 throw CoreException(std::string(sid) + " is not a valid server ID. A server ID must be 3 characters long, with the first character a digit and the next two characters a digit or letter.");
422         }
423
424         strlcpy(conf->sid, sid, 5);
425
426         return true;
427 }
428
429 static bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
430 {
431         conf->WhoWasMaxKeep = ServerInstance->Duration(data.GetString());
432
433         if (conf->WhoWasGroupSize < 0)
434                 conf->WhoWasGroupSize = 0;
435
436         if (conf->WhoWasMaxGroups < 0)
437                 conf->WhoWasMaxGroups = 0;
438
439         if (conf->WhoWasMaxKeep < 3600)
440         {
441                 conf->WhoWasMaxKeep = 3600;
442                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
443         }
444
445         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
446         if (whowas)
447         {
448                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
449         }
450
451         return true;
452 }
453
454 /* Callback called to process a single <uline> tag
455  */
456 static bool DoULine(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
457 {
458         const char* server = values[0].GetString();
459         const bool silent = values[1].GetBool();
460         conf->ulines[server] = silent;
461         return true;
462 }
463
464 /* Callback called to process a single <banlist> tag
465  */
466 static bool DoMaxBans(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
467 {
468         const char* channel = values[0].GetString();
469         int limit = values[1].GetInteger();
470         conf->maxbans[channel] = limit;
471         return true;
472 }
473
474 static bool DoZLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
475 {
476         const char* reason = values[0].GetString();
477         const char* ipmask = values[1].GetString();
478
479         ZLine* zl = new ZLine(ServerInstance->Time(), 0, "<Config>", reason, ipmask);
480         if (!ServerInstance->XLines->AddLine(zl, NULL))
481                 delete zl;
482
483         return true;
484 }
485
486 static bool DoQLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
487 {
488         const char* reason = values[0].GetString();
489         const char* nick = values[1].GetString();
490
491         QLine* ql = new QLine(ServerInstance->Time(), 0, "<Config>", reason, nick);
492         if (!ServerInstance->XLines->AddLine(ql, NULL))
493                 delete ql;
494
495         return true;
496 }
497
498 static bool DoKLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
499 {
500         const char* reason = values[0].GetString();
501         const char* host = values[1].GetString();
502
503         XLineManager* xlm = ServerInstance->XLines;
504
505         IdentHostPair ih = xlm->IdentSplit(host);
506
507         KLine* kl = new KLine(ServerInstance->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
508         if (!xlm->AddLine(kl, NULL))
509                 delete kl;
510         return true;
511 }
512
513 static bool DoELine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
514 {
515         const char* reason = values[0].GetString();
516         const char* host = values[1].GetString();
517
518         XLineManager* xlm = ServerInstance->XLines;
519
520         IdentHostPair ih = xlm->IdentSplit(host);
521
522         ELine* el = new ELine(ServerInstance->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
523         if (!xlm->AddLine(el, NULL))
524                 delete el;
525         return true;
526 }
527
528 static bool DoType(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
529 {
530         const char* TypeName = values[0].GetString();
531         const char* Classes = values[1].GetString();
532
533         conf->opertypes[TypeName] = std::string(Classes);
534         return true;
535 }
536
537 static bool DoClass(ServerConfig* conf, const char* tag, const char**, ValueList &values, int*)
538 {
539         const char* ClassName = values[0].GetString();
540         const char* CommandList = values[1].GetString();
541         const char* UModeList = values[2].GetString();
542         const char* CModeList = values[3].GetString();
543         const char *PrivsList = values[4].GetString();
544
545         for (const char* c = UModeList; *c; ++c)
546         {
547                 if ((*c < 'A' || *c > 'z') && *c != '*')
548                 {
549                         throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
550                 }
551         }
552         for (const char* c = CModeList; *c; ++c)
553         {
554                 if ((*c < 'A' || *c > 'z') && *c != '*')
555                 {
556                         throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
557                 }
558         }
559
560         conf->operclass[ClassName].commandlist = CommandList;
561         conf->operclass[ClassName].umodelist = UModeList;
562         conf->operclass[ClassName].cmodelist = CModeList;
563         conf->operclass[ClassName].privs = PrivsList;
564         return true;
565 }
566
567 void ServerConfig::CrossCheckOperClassType()
568 {
569         for (int i = 0; i < ConfValueEnum("type"); ++i)
570         {
571                 char item[MAXBUF], classn[MAXBUF], classes[MAXBUF];
572                 std::string classname;
573                 ConfValue("type", "classes", "", i, classes, MAXBUF, false);
574                 irc::spacesepstream str(classes);
575                 ConfValue("type", "name", "", i, item, MAXBUF, false);
576                 while (str.GetToken(classname))
577                 {
578                         std::string lost;
579                         bool foundclass = false;
580                         for (int j = 0; j < ConfValueEnum("class"); ++j)
581                         {
582                                 ConfValue("class", "name", "", j, classn, MAXBUF, false);
583                                 if (!strcmp(classn, classname.c_str()))
584                                 {
585                                         foundclass = true;
586                                         break;
587                                 }
588                         }
589                         if (!foundclass)
590                         {
591                                 char msg[MAXBUF];
592                                 snprintf(msg, MAXBUF, " Warning: Oper type '%s' has a missing class named '%s', this does nothing!\n",
593                                         item, classname.c_str());
594                                 throw CoreException(msg);
595                         }
596                 }
597         }
598 }
599
600 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
601 {
602         typedef std::map<std::string, ConnectClass*> ClassMap;
603         ClassMap oldBlocksByMask;
604         if (current)
605         {
606                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
607                 {
608                         ConnectClass* c = *i;
609                         std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
610                         typeMask += c->host;
611                         oldBlocksByMask[typeMask] = c;
612                 }
613         }
614
615         int block_count = ConfValueEnum("connect");
616         ClassMap newBlocksByMask;
617         Classes.resize(block_count, NULL);
618         std::map<std::string, int> names;
619
620         bool try_again = true;
621         for(int tries=0; try_again && tries < block_count + 1; tries++)
622         {
623                 try_again = false;
624                 for(int i=0; i < block_count; i++)
625                 {
626                         if (Classes[i])
627                                 continue;
628
629                         ConnectClass* parent = NULL;
630                         std::string parentName;
631                         if (ConfValue("connect", "parent", i, parentName, false))
632                         {
633                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
634                                 if (parentIter == names.end())
635                                 {
636                                         try_again = true;
637                                         // couldn't find parent this time. If it's the last time, we'll never find it.
638                                         if (tries == block_count)
639                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
640                                         continue;
641                                 }
642                                 parent = Classes[parentIter->second];
643                         }
644
645                         std::string name;
646                         if (ConfValue("connect", "name", i, name, false))
647                         {
648                                 if (names.find(name) != names.end())
649                                         throw CoreException("Two connect classes with name \"" + name + "\" defined!");
650                                 names[name] = i;
651                         }
652
653                         std::string mask, typeMask;
654                         char type;
655
656                         if (ConfValue("connect", "allow", i, mask, false))
657                         {
658                                 type = CC_ALLOW;
659                                 typeMask = 'a' + mask;
660                         }
661                         else if (ConfValue("connect", "deny", i, mask, false))
662                         {
663                                 type = CC_DENY;
664                                 typeMask = 'd' + mask;
665                         }
666                         else
667                         {
668                                 throw CoreException("Connect class must have an allow or deny mask (#" + ConvToStr(i) + ")");
669                         }
670                         ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
671                         if (dupMask != newBlocksByMask.end())
672                                 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
673
674                         ConnectClass* me = parent ? 
675                                 new ConnectClass(type, mask, *parent) :
676                                 new ConnectClass(type, mask);
677
678                         if (!name.empty())
679                                 me->name = name;
680
681                         std::string tmpv;
682                         if (ConfValue("connect", "password", i, tmpv, false))
683                                 me->pass= tmpv;
684                         if (ConfValue("connect", "hash", i, tmpv, false))
685                                 me->hash = tmpv;
686                         if (ConfValue("connect", "timeout", i, tmpv, false))
687                                 me->registration_timeout = atol(tmpv.c_str());
688                         if (ConfValue("connect", "pingfreq", i, tmpv, false))
689                                 me->pingtime = atol(tmpv.c_str());
690                         if (ConfValue("connect", "sendq", i, tmpv, false))
691                         {
692                                 // attempt to guess a good hard/soft sendq from a single value
693                                 long value = atol(tmpv.c_str());
694                                 if (value > 16384)
695                                         me->softsendqmax = value / 16;
696                                 else
697                                         me->softsendqmax = value;
698                                 me->hardsendqmax = value * 8;
699                         }
700                         if (ConfValue("connect", "softsendq", i, tmpv, false))
701                                 me->softsendqmax = atol(tmpv.c_str());
702                         if (ConfValue("connect", "hardsendq", i, tmpv, false))
703                                 me->hardsendqmax = atol(tmpv.c_str());
704                         if (ConfValue("connect", "recvq", i, tmpv, false))
705                                 me->recvqmax = atol(tmpv.c_str());
706                         if (ConfValue("connect", "localmax", i, tmpv, false))
707                                 me->maxlocal = atol(tmpv.c_str());
708                         if (ConfValue("connect", "globalmax", i, tmpv, false))
709                                 me->maxglobal = atol(tmpv.c_str());
710                         if (ConfValue("connect", "port", i, tmpv, false))
711                                 me->port = atol(tmpv.c_str());
712                         if (ConfValue("connect", "maxchans", i, tmpv, false))
713                                 me->maxchans = atol(tmpv.c_str());
714                         if (ConfValue("connect", "limit", i, tmpv, false))
715                                 me->limit = atol(tmpv.c_str());
716
717                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
718                         if (oldMask != oldBlocksByMask.end())
719                         {
720                                 ConnectClass* old = oldMask->second;
721                                 oldBlocksByMask.erase(oldMask);
722                                 old->Update(me);
723                                 delete me;
724                                 me = old;
725                         }
726                         newBlocksByMask[typeMask] = me;
727                         Classes[i] = me;
728                 }
729         }
730 }
731
732
733 static const Deprecated ChangedConfig[] = {
734         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
735         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
736         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
737         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
738         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
739         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
740         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
741         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
742         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
743         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
744         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
745         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
746         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
747         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
748         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
749         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
750         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
751         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
752         {"die",     "value",            "has always been deprecated"},
753 };
754
755 /* These tags can occur ONCE or not at all */
756 static const InitialConfig Values[] = {
757         {"performance", "softlimit",    "0",                    new ValueContainerUInt (&ServerConfig::SoftLimit),              DT_INTEGER,  ValidateSoftLimit},
758         {"performance", "somaxconn",    SOMAXCONN_S,            new ValueContainerInt  (&ServerConfig::MaxConn),                DT_INTEGER,  ValidateMaxConn},
759         {"options",     "moronbanner",  "You're banned!",       new ValueContainerChar (&ServerConfig::MoronBanner),            DT_CHARPTR,  NULL},
760         {"server",      "name",         "",                     new ValueContainerChar (&ServerConfig::ServerName),             DT_HOSTNAME, ValidateServerName},
761         {"server",      "description",  "Configure Me",         new ValueContainerChar (&ServerConfig::ServerDesc),             DT_CHARPTR,  NULL},
762         {"server",      "network",      "Network",              new ValueContainerChar (&ServerConfig::Network),                        DT_NOSPACES, NULL},
763         {"server",      "id",           "",                     new ValueContainerChar (&ServerConfig::sid),                    DT_CHARPTR,  ValidateSID},
764         {"admin",       "name",         "",                     new ValueContainerChar (&ServerConfig::AdminName),              DT_CHARPTR,  NULL},
765         {"admin",       "email",        "Mis@configu.red",      new ValueContainerChar (&ServerConfig::AdminEmail),             DT_CHARPTR,  NULL},
766         {"admin",       "nick",         "Misconfigured",        new ValueContainerChar (&ServerConfig::AdminNick),              DT_CHARPTR,  NULL},
767         {"files",       "motd",         "",                     new ValueContainerChar (&ServerConfig::motd),                   DT_CHARPTR,  ValidateMotd},
768         {"files",       "rules",        "",                     new ValueContainerChar (&ServerConfig::rules),                  DT_CHARPTR,  ValidateRules},
769         {"power",       "diepass",      "",                     new ValueContainerChar (&ServerConfig::diepass),                        DT_CHARPTR,  ValidateNotEmpty},
770         {"power",       "pause",        "",                     new ValueContainerInt  (&ServerConfig::DieDelay),               DT_INTEGER,  NULL},
771         {"power",       "hash",         "",                     new ValueContainerChar (&ServerConfig::powerhash),              DT_CHARPTR,  NULL},
772         {"power",       "restartpass",  "",                     new ValueContainerChar (&ServerConfig::restartpass),            DT_CHARPTR,  ValidateNotEmpty},
773         {"options",     "prefixquit",   "",                     new ValueContainerChar (&ServerConfig::PrefixQuit),             DT_CHARPTR,  NULL},
774         {"options",     "suffixquit",   "",                     new ValueContainerChar (&ServerConfig::SuffixQuit),             DT_CHARPTR,  NULL},
775         {"options",     "fixedquit",    "",                     new ValueContainerChar (&ServerConfig::FixedQuit),              DT_CHARPTR,  NULL},
776         {"options",     "prefixpart",   "",                     new ValueContainerChar (&ServerConfig::PrefixPart),             DT_CHARPTR,  NULL},
777         {"options",     "suffixpart",   "",                     new ValueContainerChar (&ServerConfig::SuffixPart),             DT_CHARPTR,  NULL},
778         {"options",     "fixedpart",    "",                     new ValueContainerChar (&ServerConfig::FixedPart),              DT_CHARPTR,  NULL},
779         {"performance", "netbuffersize","10240",                new ValueContainerInt  (&ServerConfig::NetBufferSize),          DT_INTEGER,  ValidateNetBufferSize},
780         {"performance", "maxwho",       "1024",                 new ValueContainerInt  (&ServerConfig::MaxWhoResults),          DT_INTEGER,  ValidateMaxWho},
781         {"options",     "allowhalfop",  "0",                    new ValueContainerBool (&ServerConfig::AllowHalfop),            DT_BOOLEAN,  ValidateHalfOp},
782         {"dns",         "server",       "",                     new ValueContainerChar (&ServerConfig::DNSServer),              DT_IPADDRESS,ValidateDnsServer},
783         {"dns",         "timeout",      "5",                    new ValueContainerInt  (&ServerConfig::dns_timeout),            DT_INTEGER,  NULL},
784         {"options",     "moduledir",    MOD_PATH,               new ValueContainerString (&ServerConfig::ModPath),                      DT_CHARPTR,  NULL},
785         {"disabled",    "commands",     "",                     new ValueContainerChar (&ServerConfig::DisabledCommands),       DT_CHARPTR,  NULL},
786         {"disabled",    "usermodes",    "",                     NULL, DT_NOTHING,  ValidateDisabledUModes},
787         {"disabled",    "chanmodes",    "",                     NULL, DT_NOTHING,  ValidateDisabledCModes},
788         {"disabled",    "fakenonexistant",      "0",            new ValueContainerBool (&ServerConfig::DisabledDontExist),              DT_BOOLEAN,  NULL},
789
790         {"security",            "runasuser",    "",             new ValueContainerChar(&ServerConfig::SetUser),                         DT_CHARPTR, NULL},
791         {"security",            "runasgroup",   "",             new ValueContainerChar(&ServerConfig::SetGroup),                                DT_CHARPTR, NULL},
792         {"security",    "userstats",    "",                     new ValueContainerChar (&ServerConfig::UserStats),              DT_CHARPTR,  NULL},
793         {"security",    "customversion","",                     new ValueContainerChar (&ServerConfig::CustomVersion),          DT_CHARPTR,  NULL},
794         {"security",    "hidesplits",   "0",                    new ValueContainerBool (&ServerConfig::HideSplits),             DT_BOOLEAN,  NULL},
795         {"security",    "hidebans",     "0",                    new ValueContainerBool (&ServerConfig::HideBans),               DT_BOOLEAN,  NULL},
796         {"security",    "hidewhois",    "",                     new ValueContainerChar (&ServerConfig::HideWhoisServer),                DT_NOSPACES, NULL},
797         {"security",    "hidekills",    "",                     new ValueContainerChar (&ServerConfig::HideKillsServer),                DT_NOSPACES,  NULL},
798         {"security",    "operspywhois", "0",                    new ValueContainerBool (&ServerConfig::OperSpyWhois),           DT_BOOLEAN,  NULL},
799         {"security",    "restrictbannedusers",  "1",            new ValueContainerBool (&ServerConfig::RestrictBannedUsers),            DT_BOOLEAN,  NULL},
800         {"security",    "genericoper",  "0",                    new ValueContainerBool (&ServerConfig::GenericOper),            DT_BOOLEAN,  NULL},
801         {"performance", "nouserdns",    "0",                    new ValueContainerBool (&ServerConfig::NoUserDns),              DT_BOOLEAN,  NULL},
802         {"options",     "syntaxhints",  "0",                    new ValueContainerBool (&ServerConfig::SyntaxHints),            DT_BOOLEAN,  NULL},
803         {"options",     "cyclehosts",   "0",                    new ValueContainerBool (&ServerConfig::CycleHosts),             DT_BOOLEAN,  NULL},
804         {"options",     "ircumsgprefix","0",                    new ValueContainerBool (&ServerConfig::UndernetMsgPrefix),      DT_BOOLEAN,  NULL},
805         {"security",    "announceinvites", "1",                 NULL, DT_NOTHING,  ValidateInvite},
806         {"options",     "hostintopic",  "1",                    new ValueContainerBool (&ServerConfig::FullHostInTopic),        DT_BOOLEAN,  NULL},
807         {"security",    "hidemodes",    "",                     NULL, DT_NOTHING,  ValidateModeLists},
808         {"options",     "exemptchanops","",                     NULL, DT_NOTHING,  ValidateExemptChanOps},
809         {"security",    "maxtargets",   "20",                   new ValueContainerUInt (&ServerConfig::MaxTargets),             DT_INTEGER,  ValidateMaxTargets},
810         {"options",     "defaultmodes", "nt",                   new ValueContainerChar (&ServerConfig::DefaultModes),           DT_CHARPTR,  NULL},
811         {"pid",         "file",         "",                     new ValueContainerString (&ServerConfig::PID),                  DT_CHARPTR,  NULL},
812         {"whowas",      "groupsize",    "10",                   new ValueContainerInt  (&ServerConfig::WhoWasGroupSize),        DT_INTEGER,  NULL},
813         {"whowas",      "maxgroups",    "10240",                new ValueContainerInt  (&ServerConfig::WhoWasMaxGroups),        DT_INTEGER,  NULL},
814         {"whowas",      "maxkeep",      "3600",                 NULL, DT_NOTHING,  ValidateWhoWas},
815         {"die",         "value",        "",                     new ValueContainerChar (&ServerConfig::DieValue),               DT_CHARPTR,  NULL},
816         {"channels",    "users",        "20",                   new ValueContainerUInt (&ServerConfig::MaxChans),               DT_INTEGER,  NULL},
817         {"channels",    "opers",        "60",                   new ValueContainerUInt (&ServerConfig::OperMaxChans),           DT_INTEGER,  NULL},
818         {"cidr",        "ipv4clone",    "32",                   new ValueContainerInt (&ServerConfig::c_ipv4_range),            DT_INTEGER,  NULL},
819         {"cidr",        "ipv6clone",    "128",                  new ValueContainerInt (&ServerConfig::c_ipv6_range),            DT_INTEGER,  NULL},
820         {"limits",      "maxnick",      "32",                   new ValueContainerLimit (&ServerLimits::NickMax),               DT_LIMIT,  NULL},
821         {"limits",      "maxchan",      "64",                   new ValueContainerLimit (&ServerLimits::ChanMax),               DT_LIMIT,  NULL},
822         {"limits",      "maxmodes",     "20",                   new ValueContainerLimit (&ServerLimits::MaxModes),              DT_LIMIT,  NULL},
823         {"limits",      "maxident",     "11",                   new ValueContainerLimit (&ServerLimits::IdentMax),              DT_LIMIT,  NULL},
824         {"limits",      "maxquit",      "255",                  new ValueContainerLimit (&ServerLimits::MaxQuit),               DT_LIMIT,  NULL},
825         {"limits",      "maxtopic",     "307",                  new ValueContainerLimit (&ServerLimits::MaxTopic),              DT_LIMIT,  NULL},
826         {"limits",      "maxkick",      "255",                  new ValueContainerLimit (&ServerLimits::MaxKick),               DT_LIMIT,  NULL},
827         {"limits",      "maxgecos",     "128",                  new ValueContainerLimit (&ServerLimits::MaxGecos),              DT_LIMIT,  NULL},
828         {"limits",      "maxaway",      "200",                  new ValueContainerLimit (&ServerLimits::MaxAway),               DT_LIMIT,  NULL},
829         {"options",     "invitebypassmodes",    "1",                    new ValueContainerBool (&ServerConfig::InvBypassModes),         DT_BOOLEAN,  NULL},
830 };
831
832 /* These tags can occur multiple times, and therefore they have special code to read them
833  * which is different to the code for reading the singular tags listed above.
834  */
835 MultiConfig MultiValues[] = {
836
837         {"connect",
838                         {"allow",       "deny",         "password",     "timeout",      "pingfreq",
839                         "sendq",        "recvq",        "localmax",     "globalmax",    "port",
840                         "name",         "parent",       "maxchans",     "limit",        "hash",
841                         NULL},
842                         {"",            "",                             "",                     "",                     "120",
843                          "",            "",                             "3",            "3",            "0",
844                          "",            "",                             "0",        "0",                "",
845                          NULL},
846                         {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR,    DT_INTEGER,     DT_INTEGER,
847                         DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
848                         DT_NOSPACES,    DT_NOSPACES,    DT_INTEGER,     DT_INTEGER,     DT_CHARPTR},
849                         NULL,},
850
851         {"uline",
852                         {"server",      "silent",       NULL},
853                         {"",            "0",            NULL},
854                         {DT_HOSTNAME,   DT_BOOLEAN},
855                         DoULine},
856
857         {"banlist",
858                         {"chan",        "limit",        NULL},
859                         {"",            "",             NULL},
860                         {DT_CHARPTR,    DT_INTEGER},
861                         DoMaxBans},
862
863         {"module",
864                         {"name",        NULL},
865                         {"",            NULL},
866                         {DT_CHARPTR},
867                         NULL},
868
869         {"badip",
870                         {"reason",      "ipmask",       NULL},
871                         {"No reason",   "",             NULL},
872                         {DT_CHARPTR,    DT_IPADDRESS|DT_ALLOW_WILD},
873                         DoZLine},
874
875         {"badnick",
876                         {"reason",      "nick",         NULL},
877                         {"No reason",   "",             NULL},
878                         {DT_CHARPTR,    DT_CHARPTR},
879                         DoQLine},
880
881         {"badhost",
882                         {"reason",      "host",         NULL},
883                         {"No reason",   "",             NULL},
884                         {DT_CHARPTR,    DT_CHARPTR},
885                         DoKLine},
886
887         {"exception",
888                         {"reason",      "host",         NULL},
889                         {"No reason",   "",             NULL},
890                         {DT_CHARPTR,    DT_CHARPTR},
891                         DoELine},
892
893         {"type",
894                         {"name",        "classes",      NULL},
895                         {"",            "",             NULL},
896                         {DT_NOSPACES,   DT_CHARPTR},
897                         DoType},
898
899         {"class",
900                         {"name",        "commands",     "usermodes",    "chanmodes",    "privs",        NULL},
901                         {"",            "",                             "",                             "",                     "",                     NULL},
902                         {DT_NOSPACES,   DT_CHARPTR,     DT_CHARPTR,     DT_CHARPTR, DT_CHARPTR},
903                         DoClass},
904 };
905
906 /* These tags MUST occur and must ONLY occur once in the config file */
907 static const char* Once[] = { "server", "admin", "files", "power", "options" };
908
909 // WARNING: it is not safe to use most of the codebase in this function, as it
910 // will run in the config reader thread
911 void ServerConfig::Read()
912 {
913         /* Load and parse the config file, if there are any errors then explode */
914
915         if (!this->DoInclude(ServerInstance->ConfigFileName, true))
916         {
917                 valid = false;
918                 return;
919         }
920 }
921
922 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
923 {
924         valid = true;
925         /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
926         errstr.clear();
927         errstr.str().clear();
928         include_stack.clear();
929
930         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
931         try
932         {
933                 /* Check we dont have more than one of singular tags, or any of them missing
934                  */
935                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
936                         CheckOnce(Once[Index]);
937
938                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
939                 {
940                         char item[MAXBUF];
941                         *item = 0;
942                         if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
943                                 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
944                 }
945
946                 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
947                  */
948                 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
949                 {
950                         char item[MAXBUF];
951                         int dt = Values[Index].datatype;
952                         bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
953                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
954                         dt &= ~DT_ALLOW_NEWLINE;
955                         dt &= ~DT_ALLOW_WILD;
956
957                         ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
958                         ValueItem vi(item);
959
960                         if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
961                                 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
962
963                         switch (dt)
964                         {
965                                 case DT_NOSPACES:
966                                 {
967                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
968                                         ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
969                                         vcc->Set(this, vi);
970                                 }
971                                 break;
972                                 case DT_HOSTNAME:
973                                 {
974                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
975                                         ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
976                                         vcc->Set(this, vi);
977                                 }
978                                 break;
979                                 case DT_IPADDRESS:
980                                 {
981                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
982                                         ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
983                                         vcc->Set(this, vi);
984                                 }
985                                 break;
986                                 case DT_CHANNEL:
987                                 {
988                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
989                                         if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
990                                         {
991                                                 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
992                                         }
993                                         vcc->Set(this, vi);
994                                 }
995                                 break;
996                                 case DT_CHARPTR:
997                                 {
998                                         ValueContainerChar* vcc = dynamic_cast<ValueContainerChar*>(Values[Index].val);
999                                         if (vcc)
1000                                                 vcc->Set(this, vi);
1001                                         ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
1002                                         if (vcs)
1003                                                 vcs->Set(this, vi.GetValue());
1004                                 }
1005                                 break;
1006                                 case DT_INTEGER:
1007                                 {
1008                                         int val = vi.GetInteger();
1009                                         ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1010                                         vci->Set(this, val);
1011                                 }
1012                                 break;
1013                                 case DT_LIMIT:
1014                                 {
1015                                         int val = vi.GetInteger();
1016                                         ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1017                                         vci->Set(this, val);
1018                                 }
1019                                 break;
1020                                 case DT_BOOLEAN:
1021                                 {
1022                                         bool val = vi.GetBool();
1023                                         ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1024                                         vcb->Set(this, val);
1025                                 }
1026                                 break;
1027                         }
1028                 }
1029
1030                 /* Read the multiple-tag items (class tags, connect tags, etc)
1031                  * and call the callbacks associated with them. We have three
1032                  * callbacks for these, a 'start', 'item' and 'end' callback.
1033                  */
1034                 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1035                 {
1036                         int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1037
1038                         for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1039                         {
1040                                 ValueList vl;
1041                                 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1042                                 {
1043                                         int dt = MultiValues[Index].datatype[valuenum];
1044                                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
1045                                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1046                                         dt &= ~DT_ALLOW_NEWLINE;
1047                                         dt &= ~DT_ALLOW_WILD;
1048
1049                                         switch (dt)
1050                                         {
1051                                                 case DT_NOSPACES:
1052                                                 {
1053                                                         char item[MAXBUF];
1054                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1055                                                                 vl.push_back(ValueItem(item));
1056                                                         else
1057                                                                 vl.push_back(ValueItem(""));
1058                                                         ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1059                                                 }
1060                                                 break;
1061                                                 case DT_HOSTNAME:
1062                                                 {
1063                                                         char item[MAXBUF];
1064                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1065                                                                 vl.push_back(ValueItem(item));
1066                                                         else
1067                                                                 vl.push_back(ValueItem(""));
1068                                                         ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1069                                                 }
1070                                                 break;
1071                                                 case DT_IPADDRESS:
1072                                                 {
1073                                                         char item[MAXBUF];
1074                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1075                                                                 vl.push_back(ValueItem(item));
1076                                                         else
1077                                                                 vl.push_back(ValueItem(""));
1078                                                         ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1079                                                 }
1080                                                 break;
1081                                                 case DT_CHANNEL:
1082                                                 {
1083                                                         char item[MAXBUF];
1084                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1085                                                                 vl.push_back(ValueItem(item));
1086                                                         else
1087                                                                 vl.push_back(ValueItem(""));
1088                                                         if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1089                                                                 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1090                                                 }
1091                                                 break;
1092                                                 case DT_CHARPTR:
1093                                                 {
1094                                                         char item[MAXBUF];
1095                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1096                                                                 vl.push_back(ValueItem(item));
1097                                                         else
1098                                                                 vl.push_back(ValueItem(""));
1099                                                 }
1100                                                 break;
1101                                                 case DT_INTEGER:
1102                                                 {
1103                                                         int item = 0;
1104                                                         if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1105                                                                 vl.push_back(ValueItem(item));
1106                                                         else
1107                                                                 vl.push_back(ValueItem(0));
1108                                                 }
1109                                                 break;
1110                                                 case DT_BOOLEAN:
1111                                                 {
1112                                                         bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1113                                                         vl.push_back(ValueItem(item));
1114                                                 }
1115                                                 break;
1116                                         }
1117                                 }
1118                                 if (MultiValues[Index].validation_function)
1119                                         MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1120                         }
1121                 }
1122
1123                 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1124                  * rather than assign(str, 0, val + 1)
1125                  */
1126                 Limits.Finalise();
1127
1128                 // Handle special items
1129                 CrossCheckOperClassType();
1130                 CrossCheckConnectBlocks(old);
1131         }
1132         catch (CoreException &ce)
1133         {
1134                 errstr << ce.GetReason();
1135                 valid = false;
1136         }
1137
1138         // write once here, to try it out and make sure its ok
1139         ServerInstance->WritePID(this->PID);
1140
1141         /*
1142          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1143          */
1144         if (old)
1145         {
1146                 memcpy(this->ServerName, old->ServerName, sizeof(this->ServerName));
1147                 memcpy(this->sid, old->sid, sizeof(this->sid));
1148                 this->argv = old->argv;
1149                 this->argc = old->argc;
1150
1151                 // Same for ports... they're bound later on first run.
1152                 FailedPortList pl;
1153                 ServerInstance->BindPorts(pl);
1154                 if (pl.size())
1155                 {
1156                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1157
1158                         int j = 1;
1159                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1160                         {
1161                                 char buf[MAXBUF];
1162                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1163                                 errstr << buf;
1164                         }
1165                 }
1166         }
1167
1168         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1169
1170         valid = errstr.str().empty();
1171         if (!valid)
1172                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1173
1174         while (errstr.good())
1175         {
1176                 std::string line;
1177                 getline(errstr, line, '\n');
1178                 if (!line.empty())
1179                 {
1180                         if (user)
1181                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1182                         else
1183                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1184                 }
1185
1186                 if (!old)
1187                 {
1188                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1189                         printf("%s\n", line.c_str());
1190                 }
1191         }
1192
1193         errstr.clear();
1194         errstr.str(std::string());
1195
1196         /* No old configuration -> initial boot, nothing more to do here */
1197         if (!old)
1198         {
1199                 if (!valid)
1200                 {
1201                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1202                 }
1203
1204                 return;
1205         }
1206
1207         // If there were errors processing configuration, don't touch modules.
1208         if (!valid)
1209                 return;
1210
1211         ApplyModules(user);
1212 }
1213
1214 void ServerConfig::ApplyModules(User* user)
1215 {
1216         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1217         std::vector<std::string> added_modules;
1218         std::set<std::string> removed_modules(v.begin(), v.end());
1219
1220         int new_module_count = ConfValueEnum("module");
1221         for(int i=0; i < new_module_count; i++)
1222         {
1223                 std::string name;
1224                 if (ConfValue("module", "name", i, name, false))
1225                 {
1226                         // if this module is already loaded, the erase will succeed, so we need do nothing
1227                         // otherwise, we need to add the module (which will be done later)
1228                         if (removed_modules.erase(name) == 0)
1229                                 added_modules.push_back(name);
1230                 }
1231         }
1232
1233         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1234         {
1235                 // Don't remove cmd_*.so, just remove m_*.so
1236                 if (removing->c_str()[0] == 'c')
1237                         continue;
1238                 if (ServerInstance->Modules->Unload(removing->c_str()))
1239                 {
1240                         ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1241
1242                         if (user)
1243                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1244                         else
1245                                 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully unloaded.", removing->c_str());
1246                 }
1247                 else
1248                 {
1249                         if (user)
1250                                 user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s %s :Failed to unload module %s: %s",user->nick.c_str(), removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
1251                         else
1252                                  ServerInstance->SNO->WriteToSnoMask('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1253                 }
1254         }
1255
1256         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1257         {
1258                 if (ServerInstance->Modules->Load(adding->c_str()))
1259                 {
1260                         ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1261                         if (user)
1262                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1263                         else
1264                                 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully loaded.", adding->c_str());
1265                 }
1266                 else
1267                 {
1268                         if (user)
1269                                 user->WriteNumeric(ERR_CANTLOADMODULE, "%s %s :Failed to load module %s: %s",user->nick.c_str(), adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
1270                         else
1271                                 ServerInstance->SNO->WriteToSnoMask('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1272                 }
1273         }
1274
1275         if (user)
1276                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1277         else
1278                 ServerInstance->SNO->WriteToSnoMask('a', "*** Successfully rehashed server.");
1279 }
1280
1281 bool ServerConfig::LoadConf(FILE* &conf, const char* filename, bool allowexeinc)
1282 {
1283         std::string line;
1284         char ch;
1285         long linenumber = 1;
1286         long last_successful_parse = 1;
1287         bool in_tag;
1288         bool in_quote;
1289         bool in_comment;
1290         int character_count = 0;
1291
1292         in_tag = false;
1293         in_quote = false;
1294         in_comment = false;
1295
1296         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1297
1298         /* Check if the file open failed first */
1299         if (!conf)
1300         {
1301                 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1302                 return false;
1303         }
1304
1305         for (unsigned int t = 0; t < include_stack.size(); t++)
1306         {
1307                 if (std::string(filename) == include_stack[t])
1308                 {
1309                         errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1310                         return false;
1311                 }
1312         }
1313
1314         /* It's not already included, add it to the list of files we've loaded */
1315         include_stack.push_back(filename);
1316
1317         /* Start reading characters... */
1318         while ((ch = fgetc(conf)) != EOF)
1319         {
1320                 /*
1321                  * Fix for moronic windows issue spotted by Adremelech.
1322                  * Some windows editors save text files as utf-16, which is
1323                  * a total pain in the ass to parse. Users should save in the
1324                  * right config format! If we ever see a file where the first
1325                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1326                  * this is most likely a utf-16 file. Bail out and insult user.
1327                  */
1328                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1329                 {
1330                         errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1331                         return false;
1332                 }
1333
1334                 /*
1335                  * Here we try and get individual tags on separate lines,
1336                  * this would be so easy if we just made people format
1337                  * their config files like that, but they don't so...
1338                  * We check for a '<' and then know the line is over when
1339                  * we get a '>' not inside quotes. If we find two '<' and
1340                  * no '>' then die with an error.
1341                  */
1342
1343                 if ((ch == '#') && !in_quote)
1344                         in_comment = true;
1345
1346                 switch (ch)
1347                 {
1348                         case '\n':
1349                                 if (in_quote)
1350                                         line += '\n';
1351                                 linenumber++;
1352                         case '\r':
1353                                 if (!in_quote)
1354                                         in_comment = false;
1355                         case '\0':
1356                                 continue;
1357                         case '\t':
1358                                 ch = ' ';
1359                 }
1360
1361                 if(in_comment)
1362                         continue;
1363
1364                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1365                  * Note that this WILL NOT usually allow insertion of newlines,
1366                  * because a newline is two characters long. Use it primarily to
1367                  * insert the " symbol.
1368                  *
1369                  * Note that this also involves a further check when parsing the line,
1370                  * which can be found below.
1371                  */
1372                 if ((ch == '\\') && (in_quote) && (in_tag))
1373                 {
1374                         line += ch;
1375                         char real_character;
1376                         if (!feof(conf))
1377                         {
1378                                 real_character = fgetc(conf);
1379                                 if (real_character == 'n')
1380                                         real_character = '\n';
1381                                 line += real_character;
1382                                 continue;
1383                         }
1384                         else
1385                         {
1386                                 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1387                                 return false;
1388                         }
1389                 }
1390
1391                 if (ch != '\r')
1392                         line += ch;
1393
1394                 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1395                 {
1396                         errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1397                         return false;
1398                 }
1399
1400                 if (ch == '<')
1401                 {
1402                         if (in_tag)
1403                         {
1404                                 if (!in_quote)
1405                                 {
1406                                         errstr << "The tag at location " << filename << ":" << last_successful_parse << " was valid, but there is an error in the tag which comes after it. You are possibly missing a \" or >. Please check this." << std::endl;
1407                                         return false;
1408                                 }
1409                         }
1410                         else
1411                         {
1412                                 if (in_quote)
1413                                 {
1414                                         errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1415                                         return false;
1416                                 }
1417                                 else
1418                                 {
1419                                         // errstr << "Opening new config tag on line " << linenumber << std::endl;
1420                                         in_tag = true;
1421                                 }
1422                         }
1423                 }
1424                 else if (ch == '"')
1425                 {
1426                         if (in_tag)
1427                         {
1428                                 if (in_quote)
1429                                 {
1430                                         // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1431                                         in_quote = false;
1432                                 }
1433                                 else
1434                                 {
1435                                         // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1436                                         in_quote = true;
1437                                 }
1438                         }
1439                         else
1440                         {
1441                                 if (in_quote)
1442                                 {
1443                                         errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1444                                 }
1445                                 else
1446                                 {
1447                                         errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1448                                 }
1449                         }
1450                 }
1451                 else if (ch == '>')
1452                 {
1453                         if (!in_quote)
1454                         {
1455                                 if (in_tag)
1456                                 {
1457                                         // errstr << "Closing config tag on line " << linenumber << std::endl;
1458                                         in_tag = false;
1459
1460                                         /*
1461                                          * If this finds an <include> then ParseLine can simply call
1462                                          * LoadConf() and load the included config into the same ConfigDataHash
1463                                          */
1464                                         long bl = linenumber;
1465                                         if (!this->ParseLine(filename, line, linenumber, allowexeinc))
1466                                                 return false;
1467                                         last_successful_parse = linenumber;
1468
1469                                         linenumber = bl;
1470
1471                                         line.clear();
1472                                 }
1473                                 else
1474                                 {
1475                                         errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1476                                         return false;
1477                                 }
1478                         }
1479                 }
1480         }
1481
1482         /* 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 */
1483         if (in_comment || in_quote)
1484         {
1485                 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1486                         is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1487         }
1488
1489         return true;
1490 }
1491
1492
1493 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename, bool allowexeinc)
1494 {
1495         return this->LoadConf(conf, filename.c_str(), allowexeinc);
1496 }
1497
1498 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber, bool allowexeinc)
1499 {
1500         std::string tagname;
1501         std::string current_key;
1502         std::string current_value;
1503         KeyValList results;
1504         char last_char = 0;
1505         bool got_name;
1506         bool got_key;
1507         bool in_quote;
1508
1509         got_name = got_key = in_quote = false;
1510
1511         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1512         {
1513                 if (!got_name)
1514                 {
1515                         /* We don't know the tag name yet. */
1516
1517                         if (*c != ' ')
1518                         {
1519                                 if (*c != '<')
1520                                 {
1521                                         if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1522                                                 tagname += *c;
1523                                         else
1524                                         {
1525                                                 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1526                                                 return false;
1527                                         }
1528                                 }
1529                         }
1530                         else
1531                         {
1532                                 /* We got to a space, we should have the tagname now. */
1533                                 if(tagname.length())
1534                                 {
1535                                         got_name = true;
1536                                 }
1537                         }
1538                 }
1539                 else
1540                 {
1541                         /* We have the tag name */
1542                         if (!got_key)
1543                         {
1544                                 /* We're still reading the key name */
1545                                 if ((*c != '=') && (*c != '>'))
1546                                 {
1547                                         if (*c != ' ')
1548                                         {
1549                                                 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1550                                                         current_key += *c;
1551                                                 else
1552                                                 {
1553                                                         errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1554                                                         return false;
1555                                                 }
1556                                         }
1557                                 }
1558                                 else
1559                                 {
1560                                         /* We got an '=', end of the key name. */
1561                                         got_key = true;
1562                                 }
1563                         }
1564                         else
1565                         {
1566                                 /* We have the key name, now we're looking for quotes and the value */
1567
1568                                 /* Correctly handle escaped characters here.
1569                                  * See the XXX'ed section above.
1570                                  */
1571                                 if ((*c == '\\') && (in_quote))
1572                                 {
1573                                         c++;
1574                                         if (*c == 'n')
1575                                                 current_value += '\n';
1576                                         else
1577                                                 current_value += *c;
1578                                         continue;
1579                                 }
1580                                 else if ((*c == '\\') && (!in_quote))
1581                                 {
1582                                         errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1583                                         return false;
1584                                 }
1585                                 else if ((*c == '\n') && (in_quote))
1586                                 {
1587                                         /* Got a 'real' \n, treat it as part of the value */
1588                                         current_value += '\n';
1589                                         continue;
1590                                 }
1591                                 else if ((*c == '\r') && (in_quote))
1592                                 {
1593                                         /* Got a \r, drop it */
1594                                         continue;
1595                                 }
1596
1597                                 if (*c == '"')
1598                                 {
1599                                         if (!in_quote)
1600                                         {
1601                                                 /* We're not already in a quote. */
1602                                                 in_quote = true;
1603                                         }
1604                                         else
1605                                         {
1606                                                 /* Leaving the quotes, we have the current value */
1607                                                 results.push_back(KeyVal(current_key, current_value));
1608
1609                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1610
1611                                                 in_quote = false;
1612                                                 got_key = false;
1613
1614                                                 if ((tagname == "include") && (current_key == "file"))
1615                                                 {
1616                                                         if (!this->DoInclude(current_value, allowexeinc))
1617                                                                 return false;
1618                                                 }
1619                                                 else if ((tagname == "include") && (current_key == "executable"))
1620                                                 {
1621                                                         if (!allowexeinc)
1622                                                         {
1623                                                                 errstr << "Executable includes are not allowed to use <include:executable>\n"
1624                                                                         "This could be an attempt to execute commands from a malicious remote include.\n"
1625                                                                         "If you need multiple levels of remote include, create a script to assemble the "
1626                                                                         "contents locally or include files using <include:file>\n";
1627                                                                 return false;
1628                                                         }
1629
1630                                                         /* Pipe an executable and use its stdout as config data */
1631                                                         if (!this->DoPipe(current_value))
1632                                                                 return false;
1633                                                 }
1634
1635                                                 current_key.clear();
1636                                                 current_value.clear();
1637                                         }
1638                                 }
1639                                 else
1640                                 {
1641                                         if (in_quote)
1642                                         {
1643                                                 last_char = *c;
1644                                                 current_value += *c;
1645                                         }
1646                                 }
1647                         }
1648                 }
1649         }
1650
1651         /* Finished parsing the tag, add it to the config hash */
1652         config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1653
1654         return true;
1655 }
1656
1657 bool ServerConfig::DoPipe(const std::string &file)
1658 {
1659         FILE* conf = popen(file.c_str(), "r");
1660         bool ret = false;
1661
1662         if (conf)
1663         {
1664                 ret = LoadConf(conf, file.c_str(), false);
1665                 pclose(conf);
1666         }
1667         else
1668                 errstr << "Couldn't execute: " << file << std::endl;
1669
1670         return ret;
1671 }
1672
1673 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1674 {
1675         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1676 }
1677
1678 bool ServerConfig::DoInclude(const std::string &file, bool allowexeinc)
1679 {
1680         std::string confpath;
1681         std::string newfile;
1682         std::string::size_type pos;
1683
1684         confpath = ServerInstance->ConfigFileName;
1685         newfile = file;
1686
1687         std::replace(newfile.begin(),newfile.end(),'\\','/');
1688         std::replace(confpath.begin(),confpath.end(),'\\','/');
1689
1690         if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1691         {
1692                 if((pos = confpath.rfind("/")) != std::string::npos)
1693                 {
1694                         /* Leaves us with just the path */
1695                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1696                 }
1697                 else
1698                 {
1699                         errstr << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1700                         return false;
1701                 }
1702         }
1703
1704         FILE* conf = fopen(newfile.c_str(), "r");
1705         bool ret = false;
1706
1707         if (conf)
1708         {
1709                 ret = LoadConf(conf, newfile, allowexeinc);
1710                 fclose(conf);
1711         }
1712         else
1713                 errstr << "Couldn't open config file: " << file << std::endl;
1714
1715         return ret;
1716 }
1717
1718 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1719 {
1720         return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1721 }
1722
1723 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1724 {
1725         std::string value;
1726         bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1727         strlcpy(result, value.c_str(), length);
1728         return r;
1729 }
1730
1731 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1732 {
1733         return ConfValue(tag, var, "", index, result, allow_linefeeds);
1734 }
1735
1736 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1737 {
1738         ConfigDataHash::size_type pos = index;
1739         if (pos < config_data.count(tag))
1740         {
1741                 ConfigDataHash::iterator iter = config_data.find(tag);
1742
1743                 for(int i = 0; i < index; i++)
1744                         iter++;
1745
1746                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1747                 {
1748                         if(j->first == var)
1749                         {
1750                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1751                                 {
1752                                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1753                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1754                                                 if (*n == '\n')
1755                                                         *n = ' ';
1756                                 }
1757                                 else
1758                                 {
1759                                         result = j->second;
1760                                         return true;
1761                                 }
1762                         }
1763                 }
1764                 if (!default_value.empty())
1765                 {
1766                         result = default_value;
1767                         return true;
1768                 }
1769         }
1770         else if (pos == 0)
1771         {
1772                 if (!default_value.empty())
1773                 {
1774                         result = default_value;
1775                         return true;
1776                 }
1777         }
1778         return false;
1779 }
1780
1781 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1782 {
1783         return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1784 }
1785
1786 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1787 {
1788         return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1789 }
1790
1791 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1792 {
1793         return ConfValueInteger(tag, var, "", index, result);
1794 }
1795
1796 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1797 {
1798         std::string value;
1799         std::istringstream stream;
1800         bool r = ConfValue(tag, var, default_value, index, value);
1801         stream.str(value);
1802         if(!(stream >> result))
1803                 return false;
1804         else
1805         {
1806                 if (!value.empty())
1807                 {
1808                         if (value.substr(0,2) == "0x")
1809                         {
1810                                 char* endptr;
1811
1812                                 value.erase(0,2);
1813                                 result = strtol(value.c_str(), &endptr, 16);
1814
1815                                 /* No digits found */
1816                                 if (endptr == value.c_str())
1817                                         return false;
1818                         }
1819                         else
1820                         {
1821                                 char denominator = *(value.end() - 1);
1822                                 switch (toupper(denominator))
1823                                 {
1824                                         case 'K':
1825                                                 /* Kilobytes -> bytes */
1826                                                 result = result * 1024;
1827                                         break;
1828                                         case 'M':
1829                                                 /* Megabytes -> bytes */
1830                                                 result = result * 1024 * 1024;
1831                                         break;
1832                                         case 'G':
1833                                                 /* Gigabytes -> bytes */
1834                                                 result = result * 1024 * 1024 * 1024;
1835                                         break;
1836                                 }
1837                         }
1838                 }
1839         }
1840         return r;
1841 }
1842
1843
1844 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1845 {
1846         return ConfValueBool(std::string(tag), std::string(var), "", index);
1847 }
1848
1849 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1850 {
1851         return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1852 }
1853
1854 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1855 {
1856         return ConfValueBool(tag, var, "", index);
1857 }
1858
1859 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1860 {
1861         std::string result;
1862         if(!ConfValue(tag, var, default_value, index, result))
1863                 return false;
1864
1865         return ((result == "yes") || (result == "true") || (result == "1"));
1866 }
1867
1868 int ServerConfig::ConfValueEnum(const char* tag)
1869 {
1870         return config_data.count(tag);
1871 }
1872
1873 int ServerConfig::ConfValueEnum(const std::string &tag)
1874 {
1875         return config_data.count(tag);
1876 }
1877
1878 int ServerConfig::ConfVarEnum(const char* tag, int index)
1879 {
1880         return ConfVarEnum(std::string(tag), index);
1881 }
1882
1883 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1884 {
1885         ConfigDataHash::size_type pos = index;
1886
1887         if (pos < config_data.count(tag))
1888         {
1889                 ConfigDataHash::const_iterator iter = config_data.find(tag);
1890
1891                 for(int i = 0; i < index; i++)
1892                         iter++;
1893
1894                 return iter->second.size();
1895         }
1896
1897         return 0;
1898 }
1899
1900 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1901  */
1902 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1903 {
1904         if (!fname || !*fname)
1905                 return false;
1906
1907         FILE* file = NULL;
1908         char linebuf[MAXBUF];
1909
1910         F.clear();
1911
1912         if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1913         {
1914                 std::string::size_type pos;
1915                 std::string confpath = ServerInstance->ConfigFileName;
1916                 std::string newfile = fname;
1917
1918                 if (((pos = confpath.rfind("/"))) != std::string::npos)
1919                         newfile = confpath.substr(0, pos) + std::string("/") + fname;
1920                 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1921                         newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1922
1923                 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1924
1925                 if (!FileExists(newfile.c_str()))
1926                         return false;
1927                 file =  fopen(newfile.c_str(), "r");
1928         }
1929         else
1930         {
1931                 if (!FileExists(fname))
1932                         return false;
1933                 file =  fopen(fname, "r");
1934         }
1935
1936         if (file)
1937         {
1938                 while (!feof(file))
1939                 {
1940                         if (fgets(linebuf, sizeof(linebuf), file))
1941                                 linebuf[strlen(linebuf)-1] = 0;
1942                         else
1943                                 *linebuf = 0;
1944
1945                         F.push_back(*linebuf ? linebuf : " ");
1946                 }
1947
1948                 fclose(file);
1949         }
1950         else
1951                 return false;
1952
1953         return true;
1954 }
1955
1956 bool ServerConfig::FileExists(const char* file)
1957 {
1958         struct stat sb;
1959         if (stat(file, &sb) == -1)
1960                 return false;
1961
1962         if ((sb.st_mode & S_IFDIR) > 0)
1963                 return false;
1964
1965         FILE *input;
1966         if ((input = fopen (file, "r")) == NULL)
1967                 return false;
1968         else
1969         {
1970                 fclose(input);
1971                 return true;
1972         }
1973 }
1974
1975 const char* ServerConfig::CleanFilename(const char* name)
1976 {
1977         const char* p = name + strlen(name);
1978         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1979         return (p != name ? ++p : p);
1980 }
1981
1982
1983 std::string ServerConfig::GetFullProgDir()
1984 {
1985         char buffer[PATH_MAX];
1986 #ifdef WINDOWS
1987         /* Windows has specific api calls to get the exe path that never fail.
1988          * For once, windows has something of use, compared to the POSIX code
1989          * for this, this is positively neato.
1990          */
1991         if (GetModuleFileName(NULL, buffer, MAX_PATH))
1992         {
1993                 std::string fullpath = buffer;
1994                 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1995                 return std::string(fullpath, 0, n);
1996         }
1997 #else
1998         // Get the current working directory
1999         if (getcwd(buffer, PATH_MAX))
2000         {
2001                 std::string remainder = this->argv[0];
2002
2003                 /* Does argv[0] start with /? its a full path, use it */
2004                 if (remainder[0] == '/')
2005                 {
2006                         std::string::size_type n = remainder.rfind("/inspircd");
2007                         return std::string(remainder, 0, n);
2008                 }
2009
2010                 std::string fullpath = std::string(buffer) + "/" + remainder;
2011                 std::string::size_type n = fullpath.rfind("/inspircd");
2012                 return std::string(fullpath, 0, n);
2013         }
2014 #endif
2015         return "/";
2016 }
2017
2018 std::string ServerConfig::GetSID()
2019 {
2020         return sid;
2021 }
2022
2023 ValueItem::ValueItem(int value)
2024 {
2025         std::stringstream n;
2026         n << value;
2027         v = n.str();
2028 }
2029
2030 ValueItem::ValueItem(bool value)
2031 {
2032         std::stringstream n;
2033         n << value;
2034         v = n.str();
2035 }
2036
2037 void ValueItem::Set(const std::string& value)
2038 {
2039         v = value;
2040 }
2041
2042 void ValueItem::Set(int value)
2043 {
2044         std::stringstream n;
2045         n << value;
2046         v = n.str();
2047 }
2048
2049 int ValueItem::GetInteger()
2050 {
2051         if (v.empty())
2052                 return 0;
2053         return atoi(v.c_str());
2054 }
2055
2056 const char* ValueItem::GetString() const
2057 {
2058         return v.c_str();
2059 }
2060
2061 bool ValueItem::GetBool()
2062 {
2063         return (GetInteger() || v == "yes" || v == "true");
2064 }
2065
2066
2067 void ConfigReaderThread::Run()
2068 {
2069         Config = new ServerConfig;
2070         Config->Read();
2071         done = true;
2072 }
2073
2074 void ConfigReaderThread::Finish()
2075 {
2076         ServerConfig* old = ServerInstance->Config;
2077         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
2078         ServerInstance->Logs->CloseLogs();
2079         ServerInstance->Config = this->Config;
2080         ServerInstance->Logs->OpenFileLogs();
2081         Config->Apply(old, TheUserUID);
2082
2083         if (Config->valid)
2084         {
2085                 /*
2086                  * Apply the changed configuration from the rehash.
2087                  *
2088                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
2089                  * thoroughly!!!
2090                  */
2091                 ServerInstance->XLines->CheckELines();
2092                 ServerInstance->XLines->CheckELines();
2093                 ServerInstance->XLines->ApplyLines();
2094                 ServerInstance->Res->Rehash();
2095                 ServerInstance->ResetMaxBans();
2096                 Config->ApplyDisabledCommands(Config->DisabledCommands);
2097                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2098                 FOREACH_MOD(I_OnRehash, OnRehash(user));
2099                 ServerInstance->BuildISupport();
2100
2101                 delete old;
2102         }
2103         else
2104         {
2105                 // whoops, abort!
2106                 ServerInstance->Logs->CloseLogs();
2107                 ServerInstance->Config = old;
2108                 ServerInstance->Logs->OpenFileLogs();
2109                 delete this->Config;
2110         }
2111 }
2112
2113 template<>
2114 void ValueContainer<char[MAXBUF]>::Set(ServerConfig* conf, ValueItem const& item)
2115 {
2116         strlcpy(conf->*vptr, item.GetString(), MAXBUF);
2117 }