]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
159ca598fce99bb6f24c7a40015f624ef12c7beb
[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(InspIRCd* Instance) : ServerInstance(Instance)
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 = Instance->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                 conf->GetInstance()->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() > conf->GetInstance()->SE->GetMaxFds()))
211         {
212                 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:softlimit> value is greater than %d or less than 0, set to %d.",conf->GetInstance()->SE->GetMaxFds(),conf->GetInstance()->SE->GetMaxFds());
213                 data.Set(conf->GetInstance()->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                 conf->GetInstance()->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                 conf->GetInstance()->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                                         conf->GetInstance()->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                                 conf->GetInstance()->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                         conf->GetInstance()->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         conf->GetInstance()->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                 conf->GetInstance()->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                 conf->GetInstance()->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                 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 128.");
342                 data.Set(128);
343         }
344         return true;
345 }
346
347 static bool ValidateHalfOp(ServerConfig* conf, const char*, const char*, ValueItem &data)
348 {
349         ModeHandler* mh = conf->GetInstance()->Modes->FindMode('h', MODETYPE_CHANNEL);
350         if (data.GetBool() && !mh) {
351                 conf->GetInstance()->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
352                 mh = new ModeChannelHalfOp(conf->GetInstance());
353                 conf->GetInstance()->Modes->AddMode(mh);
354         } else if (!data.GetBool() && mh) {
355                 conf->GetInstance()->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
356                 conf->GetInstance()->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         conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server id");
416
417         const char *sid = data.GetString();
418
419         if (*sid && !conf->GetInstance()->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 = conf->GetInstance()->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                 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
443         }
444
445         Module* whowas = conf->GetInstance()->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(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
480         if (!conf->GetInstance()->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(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
492         if (!conf->GetInstance()->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 = conf->GetInstance()->XLines;
504
505         IdentHostPair ih = xlm->IdentSplit(host);
506
507         KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->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 = conf->GetInstance()->XLines;
519
520         IdentHostPair ih = xlm->IdentSplit(host);
521
522         ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->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                                 me->sendqmax = atol(tmpv.c_str());
692                         if (ConfValue("connect", "recvq", i, tmpv, false))
693                                 me->recvqmax = atol(tmpv.c_str());
694                         if (ConfValue("connect", "localmax", i, tmpv, false))
695                                 me->maxlocal = atol(tmpv.c_str());
696                         if (ConfValue("connect", "globalmax", i, tmpv, false))
697                                 me->maxglobal = atol(tmpv.c_str());
698                         if (ConfValue("connect", "port", i, tmpv, false))
699                                 me->port = atol(tmpv.c_str());
700                         if (ConfValue("connect", "maxchans", i, tmpv, false))
701                                 me->maxchans = atol(tmpv.c_str());
702                         if (ConfValue("connect", "limit", i, tmpv, false))
703                                 me->limit = atol(tmpv.c_str());
704
705                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
706                         if (oldMask != oldBlocksByMask.end())
707                         {
708                                 ConnectClass* old = oldMask->second;
709                                 oldBlocksByMask.erase(oldMask);
710                                 old->Update(me);
711                                 delete me;
712                                 me = old;
713                         }
714                         newBlocksByMask[typeMask] = me;
715                         Classes[i] = me;
716                 }
717         }
718
719         for(ClassMap::iterator toRemove = oldBlocksByMask.begin(); toRemove != oldBlocksByMask.end(); toRemove++)
720         {
721                 removed_classes.push_back(toRemove->second);
722         }
723 }
724
725
726 static const Deprecated ChangedConfig[] = {
727         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
728         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
729         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
730         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
731         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
732         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
733         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
734         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
735         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
736         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
737         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
738         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
739         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
740         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
741         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
742         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
743         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
744         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
745         {"die",     "value",            "has always been deprecated"},
746 };
747
748 /* These tags can occur ONCE or not at all */
749 static const InitialConfig Values[] = {
750         {"performance", "softlimit",    "0",                    new ValueContainerUInt (&ServerConfig::SoftLimit),              DT_INTEGER,  ValidateSoftLimit},
751         {"performance", "somaxconn",    SOMAXCONN_S,            new ValueContainerInt  (&ServerConfig::MaxConn),                DT_INTEGER,  ValidateMaxConn},
752         {"options",     "moronbanner",  "You're banned!",       new ValueContainerChar (&ServerConfig::MoronBanner),            DT_CHARPTR,  NULL},
753         {"server",      "name",         "",                     new ValueContainerChar (&ServerConfig::ServerName),             DT_HOSTNAME, ValidateServerName},
754         {"server",      "description",  "Configure Me",         new ValueContainerChar (&ServerConfig::ServerDesc),             DT_CHARPTR,  NULL},
755         {"server",      "network",      "Network",              new ValueContainerChar (&ServerConfig::Network),                        DT_NOSPACES, NULL},
756         {"server",      "id",           "",                     new ValueContainerChar (&ServerConfig::sid),                    DT_CHARPTR,  ValidateSID},
757         {"admin",       "name",         "",                     new ValueContainerChar (&ServerConfig::AdminName),              DT_CHARPTR,  NULL},
758         {"admin",       "email",        "Mis@configu.red",      new ValueContainerChar (&ServerConfig::AdminEmail),             DT_CHARPTR,  NULL},
759         {"admin",       "nick",         "Misconfigured",        new ValueContainerChar (&ServerConfig::AdminNick),              DT_CHARPTR,  NULL},
760         {"files",       "motd",         "",                     new ValueContainerChar (&ServerConfig::motd),                   DT_CHARPTR,  ValidateMotd},
761         {"files",       "rules",        "",                     new ValueContainerChar (&ServerConfig::rules),                  DT_CHARPTR,  ValidateRules},
762         {"power",       "diepass",      "",                     new ValueContainerChar (&ServerConfig::diepass),                        DT_CHARPTR,  ValidateNotEmpty},
763         {"power",       "pause",        "",                     new ValueContainerInt  (&ServerConfig::DieDelay),               DT_INTEGER,  NULL},
764         {"power",       "hash",         "",                     new ValueContainerChar (&ServerConfig::powerhash),              DT_CHARPTR,  NULL},
765         {"power",       "restartpass",  "",                     new ValueContainerChar (&ServerConfig::restartpass),            DT_CHARPTR,  ValidateNotEmpty},
766         {"options",     "prefixquit",   "",                     new ValueContainerChar (&ServerConfig::PrefixQuit),             DT_CHARPTR,  NULL},
767         {"options",     "suffixquit",   "",                     new ValueContainerChar (&ServerConfig::SuffixQuit),             DT_CHARPTR,  NULL},
768         {"options",     "fixedquit",    "",                     new ValueContainerChar (&ServerConfig::FixedQuit),              DT_CHARPTR,  NULL},
769         {"options",     "prefixpart",   "",                     new ValueContainerChar (&ServerConfig::PrefixPart),             DT_CHARPTR,  NULL},
770         {"options",     "suffixpart",   "",                     new ValueContainerChar (&ServerConfig::SuffixPart),             DT_CHARPTR,  NULL},
771         {"options",     "fixedpart",    "",                     new ValueContainerChar (&ServerConfig::FixedPart),              DT_CHARPTR,  NULL},
772         {"performance", "netbuffersize","10240",                new ValueContainerInt  (&ServerConfig::NetBufferSize),          DT_INTEGER,  ValidateNetBufferSize},
773         {"performance", "maxwho",       "128",                  new ValueContainerInt  (&ServerConfig::MaxWhoResults),          DT_INTEGER,  ValidateMaxWho},
774         {"options",     "allowhalfop",  "0",                    new ValueContainerBool (&ServerConfig::AllowHalfop),            DT_BOOLEAN,  ValidateHalfOp},
775         {"dns",         "server",       "",                     new ValueContainerChar (&ServerConfig::DNSServer),              DT_IPADDRESS,ValidateDnsServer},
776         {"dns",         "timeout",      "5",                    new ValueContainerInt  (&ServerConfig::dns_timeout),            DT_INTEGER,  NULL},
777         {"options",     "moduledir",    MOD_PATH,               new ValueContainerString (&ServerConfig::ModPath),                      DT_CHARPTR,  NULL},
778         {"disabled",    "commands",     "",                     new ValueContainerChar (&ServerConfig::DisabledCommands),       DT_CHARPTR,  NULL},
779         {"disabled",    "usermodes",    "",                     NULL, DT_NOTHING,  ValidateDisabledUModes},
780         {"disabled",    "chanmodes",    "",                     NULL, DT_NOTHING,  ValidateDisabledCModes},
781         {"disabled",    "fakenonexistant",      "0",            new ValueContainerBool (&ServerConfig::DisabledDontExist),              DT_BOOLEAN,  NULL},
782
783         {"security",            "runasuser",    "",             new ValueContainerChar(&ServerConfig::SetUser),                         DT_CHARPTR, NULL},
784         {"security",            "runasgroup",   "",             new ValueContainerChar(&ServerConfig::SetGroup),                                DT_CHARPTR, NULL},
785         {"security",    "userstats",    "",                     new ValueContainerChar (&ServerConfig::UserStats),              DT_CHARPTR,  NULL},
786         {"security",    "customversion","",                     new ValueContainerChar (&ServerConfig::CustomVersion),          DT_CHARPTR,  NULL},
787         {"security",    "hidesplits",   "0",                    new ValueContainerBool (&ServerConfig::HideSplits),             DT_BOOLEAN,  NULL},
788         {"security",    "hidebans",     "0",                    new ValueContainerBool (&ServerConfig::HideBans),               DT_BOOLEAN,  NULL},
789         {"security",    "hidewhois",    "",                     new ValueContainerChar (&ServerConfig::HideWhoisServer),                DT_NOSPACES, NULL},
790         {"security",    "hidekills",    "",                     new ValueContainerChar (&ServerConfig::HideKillsServer),                DT_NOSPACES,  NULL},
791         {"security",    "operspywhois", "0",                    new ValueContainerBool (&ServerConfig::OperSpyWhois),           DT_BOOLEAN,  NULL},
792         {"security",    "restrictbannedusers",  "1",            new ValueContainerBool (&ServerConfig::RestrictBannedUsers),            DT_BOOLEAN,  NULL},
793         {"security",    "genericoper",  "0",                    new ValueContainerBool (&ServerConfig::GenericOper),            DT_BOOLEAN,  NULL},
794         {"performance", "nouserdns",    "0",                    new ValueContainerBool (&ServerConfig::NoUserDns),              DT_BOOLEAN,  NULL},
795         {"options",     "syntaxhints",  "0",                    new ValueContainerBool (&ServerConfig::SyntaxHints),            DT_BOOLEAN,  NULL},
796         {"options",     "cyclehosts",   "0",                    new ValueContainerBool (&ServerConfig::CycleHosts),             DT_BOOLEAN,  NULL},
797         {"options",     "ircumsgprefix","0",                    new ValueContainerBool (&ServerConfig::UndernetMsgPrefix),      DT_BOOLEAN,  NULL},
798         {"security",    "announceinvites", "1",                 NULL, DT_NOTHING,  ValidateInvite},
799         {"options",     "hostintopic",  "1",                    new ValueContainerBool (&ServerConfig::FullHostInTopic),        DT_BOOLEAN,  NULL},
800         {"security",    "hidemodes",    "",                     NULL, DT_NOTHING,  ValidateModeLists},
801         {"options",     "exemptchanops","",                     NULL, DT_NOTHING,  ValidateExemptChanOps},
802         {"security",    "maxtargets",   "20",                   new ValueContainerUInt (&ServerConfig::MaxTargets),             DT_INTEGER,  ValidateMaxTargets},
803         {"options",     "defaultmodes", "nt",                   new ValueContainerChar (&ServerConfig::DefaultModes),           DT_CHARPTR,  NULL},
804         {"pid",         "file",         "",                     new ValueContainerString (&ServerConfig::PID),                  DT_CHARPTR,  NULL},
805         {"whowas",      "groupsize",    "10",                   new ValueContainerInt  (&ServerConfig::WhoWasGroupSize),        DT_INTEGER,  NULL},
806         {"whowas",      "maxgroups",    "10240",                new ValueContainerInt  (&ServerConfig::WhoWasMaxGroups),        DT_INTEGER,  NULL},
807         {"whowas",      "maxkeep",      "3600",                 NULL, DT_NOTHING,  ValidateWhoWas},
808         {"die",         "value",        "",                     new ValueContainerChar (&ServerConfig::DieValue),               DT_CHARPTR,  NULL},
809         {"channels",    "users",        "20",                   new ValueContainerUInt (&ServerConfig::MaxChans),               DT_INTEGER,  NULL},
810         {"channels",    "opers",        "60",                   new ValueContainerUInt (&ServerConfig::OperMaxChans),           DT_INTEGER,  NULL},
811         {"cidr",        "ipv4clone",    "32",                   new ValueContainerInt (&ServerConfig::c_ipv4_range),            DT_INTEGER,  NULL},
812         {"cidr",        "ipv6clone",    "128",                  new ValueContainerInt (&ServerConfig::c_ipv6_range),            DT_INTEGER,  NULL},
813         {"limits",      "maxnick",      "32",                   new ValueContainerLimit (&ServerLimits::NickMax),               DT_LIMIT,  NULL},
814         {"limits",      "maxchan",      "64",                   new ValueContainerLimit (&ServerLimits::ChanMax),               DT_LIMIT,  NULL},
815         {"limits",      "maxmodes",     "20",                   new ValueContainerLimit (&ServerLimits::MaxModes),              DT_LIMIT,  NULL},
816         {"limits",      "maxident",     "11",                   new ValueContainerLimit (&ServerLimits::IdentMax),              DT_LIMIT,  NULL},
817         {"limits",      "maxquit",      "255",                  new ValueContainerLimit (&ServerLimits::MaxQuit),               DT_LIMIT,  NULL},
818         {"limits",      "maxtopic",     "307",                  new ValueContainerLimit (&ServerLimits::MaxTopic),              DT_LIMIT,  NULL},
819         {"limits",      "maxkick",      "255",                  new ValueContainerLimit (&ServerLimits::MaxKick),               DT_LIMIT,  NULL},
820         {"limits",      "maxgecos",     "128",                  new ValueContainerLimit (&ServerLimits::MaxGecos),              DT_LIMIT,  NULL},
821         {"limits",      "maxaway",      "200",                  new ValueContainerLimit (&ServerLimits::MaxAway),               DT_LIMIT,  NULL},
822         {"options",     "invitebypassmodes",    "1",                    new ValueContainerBool (&ServerConfig::InvBypassModes),         DT_BOOLEAN,  NULL},
823 };
824
825 /* These tags can occur multiple times, and therefore they have special code to read them
826  * which is different to the code for reading the singular tags listed above.
827  */
828 MultiConfig MultiValues[] = {
829
830         {"connect",
831                         {"allow",       "deny",         "password",     "timeout",      "pingfreq",
832                         "sendq",        "recvq",        "localmax",     "globalmax",    "port",
833                         "name",         "parent",       "maxchans",     "limit",        "hash",
834                         NULL},
835                         {"",            "",                             "",                     "",                     "120",
836                          "",            "",                             "3",            "3",            "0",
837                          "",            "",                             "0",        "0",                "",
838                          NULL},
839                         {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR,    DT_INTEGER,     DT_INTEGER,
840                         DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
841                         DT_NOSPACES,    DT_NOSPACES,    DT_INTEGER,     DT_INTEGER,     DT_CHARPTR},
842                         NULL,},
843
844         {"uline",
845                         {"server",      "silent",       NULL},
846                         {"",            "0",            NULL},
847                         {DT_HOSTNAME,   DT_BOOLEAN},
848                         DoULine},
849
850         {"banlist",
851                         {"chan",        "limit",        NULL},
852                         {"",            "",             NULL},
853                         {DT_CHARPTR,    DT_INTEGER},
854                         DoMaxBans},
855
856         {"module",
857                         {"name",        NULL},
858                         {"",            NULL},
859                         {DT_CHARPTR},
860                         NULL},
861
862         {"badip",
863                         {"reason",      "ipmask",       NULL},
864                         {"No reason",   "",             NULL},
865                         {DT_CHARPTR,    DT_IPADDRESS|DT_ALLOW_WILD},
866                         DoZLine},
867
868         {"badnick",
869                         {"reason",      "nick",         NULL},
870                         {"No reason",   "",             NULL},
871                         {DT_CHARPTR,    DT_CHARPTR},
872                         DoQLine},
873
874         {"badhost",
875                         {"reason",      "host",         NULL},
876                         {"No reason",   "",             NULL},
877                         {DT_CHARPTR,    DT_CHARPTR},
878                         DoKLine},
879
880         {"exception",
881                         {"reason",      "host",         NULL},
882                         {"No reason",   "",             NULL},
883                         {DT_CHARPTR,    DT_CHARPTR},
884                         DoELine},
885
886         {"type",
887                         {"name",        "classes",      NULL},
888                         {"",            "",             NULL},
889                         {DT_NOSPACES,   DT_CHARPTR},
890                         DoType},
891
892         {"class",
893                         {"name",        "commands",     "usermodes",    "chanmodes",    "privs",        NULL},
894                         {"",            "",                             "",                             "",                     "",                     NULL},
895                         {DT_NOSPACES,   DT_CHARPTR,     DT_CHARPTR,     DT_CHARPTR, DT_CHARPTR},
896                         DoClass},
897 };
898
899 /* These tags MUST occur and must ONLY occur once in the config file */
900 static const char* Once[] = { "server", "admin", "files", "power", "options" };
901
902 // WARNING: it is not safe to use most of the codebase in this function, as it
903 // will run in the config reader thread
904 void ServerConfig::Read()
905 {
906         /* Load and parse the config file, if there are any errors then explode */
907
908         if (!this->DoInclude(ServerInstance->ConfigFileName, true))
909         {
910                 valid = false;
911                 return;
912         }
913 }
914
915 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
916 {
917         valid = true;
918         /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
919         errstr.clear();
920         errstr.str().clear();
921         include_stack.clear();
922
923         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
924         try
925         {
926                 /* Check we dont have more than one of singular tags, or any of them missing
927                  */
928                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
929                         CheckOnce(Once[Index]);
930
931                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
932                 {
933                         char item[MAXBUF];
934                         *item = 0;
935                         if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
936                                 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
937                 }
938
939                 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
940                  */
941                 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
942                 {
943                         char item[MAXBUF];
944                         int dt = Values[Index].datatype;
945                         bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
946                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
947                         dt &= ~DT_ALLOW_NEWLINE;
948                         dt &= ~DT_ALLOW_WILD;
949
950                         ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
951                         ValueItem vi(item);
952
953                         if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
954                                 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
955
956                         switch (dt)
957                         {
958                                 case DT_NOSPACES:
959                                 {
960                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
961                                         ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
962                                         vcc->Set(this, vi);
963                                 }
964                                 break;
965                                 case DT_HOSTNAME:
966                                 {
967                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
968                                         ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
969                                         vcc->Set(this, vi);
970                                 }
971                                 break;
972                                 case DT_IPADDRESS:
973                                 {
974                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
975                                         ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
976                                         vcc->Set(this, vi);
977                                 }
978                                 break;
979                                 case DT_CHANNEL:
980                                 {
981                                         ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
982                                         if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
983                                         {
984                                                 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
985                                         }
986                                         vcc->Set(this, vi);
987                                 }
988                                 break;
989                                 case DT_CHARPTR:
990                                 {
991                                         ValueContainerChar* vcc = dynamic_cast<ValueContainerChar*>(Values[Index].val);
992                                         if (vcc)
993                                                 vcc->Set(this, vi);
994                                         ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
995                                         if (vcs)
996                                                 vcs->Set(this, vi.GetValue());
997                                 }
998                                 break;
999                                 case DT_INTEGER:
1000                                 {
1001                                         int val = vi.GetInteger();
1002                                         ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1003                                         vci->Set(this, val);
1004                                 }
1005                                 break;
1006                                 case DT_LIMIT:
1007                                 {
1008                                         int val = vi.GetInteger();
1009                                         ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1010                                         vci->Set(this, val);
1011                                 }
1012                                 break;
1013                                 case DT_BOOLEAN:
1014                                 {
1015                                         bool val = vi.GetBool();
1016                                         ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1017                                         vcb->Set(this, val);
1018                                 }
1019                                 break;
1020                         }
1021                 }
1022
1023                 /* Read the multiple-tag items (class tags, connect tags, etc)
1024                  * and call the callbacks associated with them. We have three
1025                  * callbacks for these, a 'start', 'item' and 'end' callback.
1026                  */
1027                 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1028                 {
1029                         int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1030
1031                         for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1032                         {
1033                                 ValueList vl;
1034                                 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1035                                 {
1036                                         int dt = MultiValues[Index].datatype[valuenum];
1037                                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
1038                                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1039                                         dt &= ~DT_ALLOW_NEWLINE;
1040                                         dt &= ~DT_ALLOW_WILD;
1041
1042                                         switch (dt)
1043                                         {
1044                                                 case DT_NOSPACES:
1045                                                 {
1046                                                         char item[MAXBUF];
1047                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1048                                                                 vl.push_back(ValueItem(item));
1049                                                         else
1050                                                                 vl.push_back(ValueItem(""));
1051                                                         ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1052                                                 }
1053                                                 break;
1054                                                 case DT_HOSTNAME:
1055                                                 {
1056                                                         char item[MAXBUF];
1057                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1058                                                                 vl.push_back(ValueItem(item));
1059                                                         else
1060                                                                 vl.push_back(ValueItem(""));
1061                                                         ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1062                                                 }
1063                                                 break;
1064                                                 case DT_IPADDRESS:
1065                                                 {
1066                                                         char item[MAXBUF];
1067                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1068                                                                 vl.push_back(ValueItem(item));
1069                                                         else
1070                                                                 vl.push_back(ValueItem(""));
1071                                                         ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1072                                                 }
1073                                                 break;
1074                                                 case DT_CHANNEL:
1075                                                 {
1076                                                         char item[MAXBUF];
1077                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1078                                                                 vl.push_back(ValueItem(item));
1079                                                         else
1080                                                                 vl.push_back(ValueItem(""));
1081                                                         if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1082                                                                 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1083                                                 }
1084                                                 break;
1085                                                 case DT_CHARPTR:
1086                                                 {
1087                                                         char item[MAXBUF];
1088                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1089                                                                 vl.push_back(ValueItem(item));
1090                                                         else
1091                                                                 vl.push_back(ValueItem(""));
1092                                                 }
1093                                                 break;
1094                                                 case DT_INTEGER:
1095                                                 {
1096                                                         int item = 0;
1097                                                         if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1098                                                                 vl.push_back(ValueItem(item));
1099                                                         else
1100                                                                 vl.push_back(ValueItem(0));
1101                                                 }
1102                                                 break;
1103                                                 case DT_BOOLEAN:
1104                                                 {
1105                                                         bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1106                                                         vl.push_back(ValueItem(item));
1107                                                 }
1108                                                 break;
1109                                         }
1110                                 }
1111                                 if (MultiValues[Index].validation_function)
1112                                         MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1113                         }
1114                 }
1115
1116                 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1117                  * rather than assign(str, 0, val + 1)
1118                  */
1119                 Limits.Finalise();
1120
1121                 // Handle special items
1122                 CrossCheckOperClassType();
1123                 CrossCheckConnectBlocks(old);
1124         }
1125         catch (CoreException &ce)
1126         {
1127                 errstr << ce.GetReason();
1128                 valid = false;
1129         }
1130
1131         // write once here, to try it out and make sure its ok
1132         ServerInstance->WritePID(this->PID);
1133
1134         FailedPortList pl;
1135         ServerInstance->BindPorts(pl);
1136
1137         /*
1138          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1139          */
1140         if (old)
1141         {
1142                 memcpy(this->ServerName, old->ServerName, sizeof(this->ServerName));
1143                 memcpy(this->sid, old->sid, sizeof(this->sid));
1144         }
1145
1146         if (pl.size())
1147         {
1148                 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1149
1150                 int j = 1;
1151                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1152                 {
1153                         char buf[MAXBUF];
1154                         snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1155                         errstr << buf;
1156                 }
1157         }
1158
1159         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1160
1161         valid = errstr.str().empty();
1162         if (!valid)
1163                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1164
1165         while (errstr.good())
1166         {
1167                 std::string line;
1168                 getline(errstr, line, '\n');
1169                 if (!line.empty())
1170                 {
1171                         if (user)
1172                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1173                         else
1174                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1175                 }
1176
1177                 if (!old)
1178                 {
1179                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1180                         printf("%s\n", line.c_str());
1181                 }
1182         }
1183
1184         errstr.clear();
1185         errstr.str(std::string());
1186
1187         /* No old configuration -> initial boot, nothing more to do here */
1188         if (!old)
1189         {
1190                 if (!valid)
1191                 {
1192                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1193                 }
1194
1195                 return;
1196         }
1197
1198         // If there were errors processing configuration, don't touch modules.
1199         if (!valid)
1200                 return;
1201
1202         ApplyModules(user);
1203         for (std::vector<ConnectClass*>::iterator i = removed_classes.begin(); i != removed_classes.end(); i++)
1204         {
1205                 ConnectClass* c = *i;
1206                 if (0 == --c->RefCount)
1207                         delete c;
1208         }
1209 }
1210
1211 void ServerConfig::ApplyModules(User* user)
1212 {
1213         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1214         std::vector<std::string> added_modules;
1215         std::set<std::string> removed_modules(v.begin(), v.end());
1216
1217         int new_module_count = ConfValueEnum("module");
1218         for(int i=0; i < new_module_count; i++)
1219         {
1220                 std::string name;
1221                 if (ConfValue("module", "name", i, name, false))
1222                 {
1223                         // if this module is already loaded, the erase will succeed, so we need do nothing
1224                         // otherwise, we need to add the module (which will be done later)
1225                         if (removed_modules.erase(name) == 0)
1226                                 added_modules.push_back(name);
1227                 }
1228         }
1229
1230         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1231         {
1232                 // Don't remove cmd_*.so, just remove m_*.so
1233                 if (removing->c_str()[0] == 'c')
1234                         continue;
1235                 if (ServerInstance->Modules->Unload(removing->c_str()))
1236                 {
1237                         ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1238
1239                         if (user)
1240                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1241                         else
1242                                 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully unloaded.", removing->c_str());
1243                 }
1244                 else
1245                 {
1246                         if (user)
1247                                 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());
1248                         else
1249                                  ServerInstance->SNO->WriteToSnoMask('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1250                 }
1251         }
1252
1253         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1254         {
1255                 if (ServerInstance->Modules->Load(adding->c_str()))
1256                 {
1257                         ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1258                         if (user)
1259                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1260                         else
1261                                 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully loaded.", adding->c_str());
1262                 }
1263                 else
1264                 {
1265                         if (user)
1266                                 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());
1267                         else
1268                                 ServerInstance->SNO->WriteToSnoMask('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1269                 }
1270         }
1271
1272         if (user)
1273                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1274         else
1275                 ServerInstance->SNO->WriteToSnoMask('a', "*** Successfully rehashed server.");
1276 }
1277
1278 bool ServerConfig::LoadConf(FILE* &conf, const char* filename, bool allowexeinc)
1279 {
1280         std::string line;
1281         char ch;
1282         long linenumber = 1;
1283         long last_successful_parse = 1;
1284         bool in_tag;
1285         bool in_quote;
1286         bool in_comment;
1287         int character_count = 0;
1288
1289         in_tag = false;
1290         in_quote = false;
1291         in_comment = false;
1292
1293         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1294
1295         /* Check if the file open failed first */
1296         if (!conf)
1297         {
1298                 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1299                 return false;
1300         }
1301
1302         for (unsigned int t = 0; t < include_stack.size(); t++)
1303         {
1304                 if (std::string(filename) == include_stack[t])
1305                 {
1306                         errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1307                         return false;
1308                 }
1309         }
1310
1311         /* It's not already included, add it to the list of files we've loaded */
1312         include_stack.push_back(filename);
1313
1314         /* Start reading characters... */
1315         while ((ch = fgetc(conf)) != EOF)
1316         {
1317                 /*
1318                  * Fix for moronic windows issue spotted by Adremelech.
1319                  * Some windows editors save text files as utf-16, which is
1320                  * a total pain in the ass to parse. Users should save in the
1321                  * right config format! If we ever see a file where the first
1322                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1323                  * this is most likely a utf-16 file. Bail out and insult user.
1324                  */
1325                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1326                 {
1327                         errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1328                         return false;
1329                 }
1330
1331                 /*
1332                  * Here we try and get individual tags on separate lines,
1333                  * this would be so easy if we just made people format
1334                  * their config files like that, but they don't so...
1335                  * We check for a '<' and then know the line is over when
1336                  * we get a '>' not inside quotes. If we find two '<' and
1337                  * no '>' then die with an error.
1338                  */
1339
1340                 if ((ch == '#') && !in_quote)
1341                         in_comment = true;
1342
1343                 switch (ch)
1344                 {
1345                         case '\n':
1346                                 if (in_quote)
1347                                         line += '\n';
1348                                 linenumber++;
1349                         case '\r':
1350                                 if (!in_quote)
1351                                         in_comment = false;
1352                         case '\0':
1353                                 continue;
1354                         case '\t':
1355                                 ch = ' ';
1356                 }
1357
1358                 if(in_comment)
1359                         continue;
1360
1361                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1362                  * Note that this WILL NOT usually allow insertion of newlines,
1363                  * because a newline is two characters long. Use it primarily to
1364                  * insert the " symbol.
1365                  *
1366                  * Note that this also involves a further check when parsing the line,
1367                  * which can be found below.
1368                  */
1369                 if ((ch == '\\') && (in_quote) && (in_tag))
1370                 {
1371                         line += ch;
1372                         char real_character;
1373                         if (!feof(conf))
1374                         {
1375                                 real_character = fgetc(conf);
1376                                 if (real_character == 'n')
1377                                         real_character = '\n';
1378                                 line += real_character;
1379                                 continue;
1380                         }
1381                         else
1382                         {
1383                                 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1384                                 return false;
1385                         }
1386                 }
1387
1388                 if (ch != '\r')
1389                         line += ch;
1390
1391                 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1392                 {
1393                         errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1394                         return false;
1395                 }
1396
1397                 if (ch == '<')
1398                 {
1399                         if (in_tag)
1400                         {
1401                                 if (!in_quote)
1402                                 {
1403                                         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;
1404                                         return false;
1405                                 }
1406                         }
1407                         else
1408                         {
1409                                 if (in_quote)
1410                                 {
1411                                         errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1412                                         return false;
1413                                 }
1414                                 else
1415                                 {
1416                                         // errstr << "Opening new config tag on line " << linenumber << std::endl;
1417                                         in_tag = true;
1418                                 }
1419                         }
1420                 }
1421                 else if (ch == '"')
1422                 {
1423                         if (in_tag)
1424                         {
1425                                 if (in_quote)
1426                                 {
1427                                         // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1428                                         in_quote = false;
1429                                 }
1430                                 else
1431                                 {
1432                                         // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1433                                         in_quote = true;
1434                                 }
1435                         }
1436                         else
1437                         {
1438                                 if (in_quote)
1439                                 {
1440                                         errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1441                                 }
1442                                 else
1443                                 {
1444                                         errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1445                                 }
1446                         }
1447                 }
1448                 else if (ch == '>')
1449                 {
1450                         if (!in_quote)
1451                         {
1452                                 if (in_tag)
1453                                 {
1454                                         // errstr << "Closing config tag on line " << linenumber << std::endl;
1455                                         in_tag = false;
1456
1457                                         /*
1458                                          * If this finds an <include> then ParseLine can simply call
1459                                          * LoadConf() and load the included config into the same ConfigDataHash
1460                                          */
1461                                         long bl = linenumber;
1462                                         if (!this->ParseLine(filename, line, linenumber, allowexeinc))
1463                                                 return false;
1464                                         last_successful_parse = linenumber;
1465
1466                                         linenumber = bl;
1467
1468                                         line.clear();
1469                                 }
1470                                 else
1471                                 {
1472                                         errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1473                                         return false;
1474                                 }
1475                         }
1476                 }
1477         }
1478
1479         /* 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 */
1480         if (in_comment || in_quote)
1481         {
1482                 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1483                         is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1484         }
1485
1486         return true;
1487 }
1488
1489
1490 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename, bool allowexeinc)
1491 {
1492         return this->LoadConf(conf, filename.c_str(), allowexeinc);
1493 }
1494
1495 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber, bool allowexeinc)
1496 {
1497         std::string tagname;
1498         std::string current_key;
1499         std::string current_value;
1500         KeyValList results;
1501         char last_char = 0;
1502         bool got_name;
1503         bool got_key;
1504         bool in_quote;
1505
1506         got_name = got_key = in_quote = false;
1507
1508         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1509         {
1510                 if (!got_name)
1511                 {
1512                         /* We don't know the tag name yet. */
1513
1514                         if (*c != ' ')
1515                         {
1516                                 if (*c != '<')
1517                                 {
1518                                         if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1519                                                 tagname += *c;
1520                                         else
1521                                         {
1522                                                 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1523                                                 return false;
1524                                         }
1525                                 }
1526                         }
1527                         else
1528                         {
1529                                 /* We got to a space, we should have the tagname now. */
1530                                 if(tagname.length())
1531                                 {
1532                                         got_name = true;
1533                                 }
1534                         }
1535                 }
1536                 else
1537                 {
1538                         /* We have the tag name */
1539                         if (!got_key)
1540                         {
1541                                 /* We're still reading the key name */
1542                                 if ((*c != '=') && (*c != '>'))
1543                                 {
1544                                         if (*c != ' ')
1545                                         {
1546                                                 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1547                                                         current_key += *c;
1548                                                 else
1549                                                 {
1550                                                         errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1551                                                         return false;
1552                                                 }
1553                                         }
1554                                 }
1555                                 else
1556                                 {
1557                                         /* We got an '=', end of the key name. */
1558                                         got_key = true;
1559                                 }
1560                         }
1561                         else
1562                         {
1563                                 /* We have the key name, now we're looking for quotes and the value */
1564
1565                                 /* Correctly handle escaped characters here.
1566                                  * See the XXX'ed section above.
1567                                  */
1568                                 if ((*c == '\\') && (in_quote))
1569                                 {
1570                                         c++;
1571                                         if (*c == 'n')
1572                                                 current_value += '\n';
1573                                         else
1574                                                 current_value += *c;
1575                                         continue;
1576                                 }
1577                                 else if ((*c == '\\') && (!in_quote))
1578                                 {
1579                                         errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1580                                         return false;
1581                                 }
1582                                 else if ((*c == '\n') && (in_quote))
1583                                 {
1584                                         /* Got a 'real' \n, treat it as part of the value */
1585                                         current_value += '\n';
1586                                         continue;
1587                                 }
1588                                 else if ((*c == '\r') && (in_quote))
1589                                 {
1590                                         /* Got a \r, drop it */
1591                                         continue;
1592                                 }
1593
1594                                 if (*c == '"')
1595                                 {
1596                                         if (!in_quote)
1597                                         {
1598                                                 /* We're not already in a quote. */
1599                                                 in_quote = true;
1600                                         }
1601                                         else
1602                                         {
1603                                                 /* Leaving the quotes, we have the current value */
1604                                                 results.push_back(KeyVal(current_key, current_value));
1605
1606                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1607
1608                                                 in_quote = false;
1609                                                 got_key = false;
1610
1611                                                 if ((tagname == "include") && (current_key == "file"))
1612                                                 {
1613                                                         if (!this->DoInclude(current_value, allowexeinc))
1614                                                                 return false;
1615                                                 }
1616                                                 else if ((tagname == "include") && (current_key == "executable"))
1617                                                 {
1618                                                         if (!allowexeinc)
1619                                                         {
1620                                                                 errstr << "Executable includes are not allowed to use <include:executable>\n"
1621                                                                         "This could be an attempt to execute commands from a malicious remote include.\n"
1622                                                                         "If you need multiple levels of remote include, create a script to assemble the "
1623                                                                         "contents locally or include files using <include:file>\n";
1624                                                                 return false;
1625                                                         }
1626
1627                                                         /* Pipe an executable and use its stdout as config data */
1628                                                         if (!this->DoPipe(current_value))
1629                                                                 return false;
1630                                                 }
1631
1632                                                 current_key.clear();
1633                                                 current_value.clear();
1634                                         }
1635                                 }
1636                                 else
1637                                 {
1638                                         if (in_quote)
1639                                         {
1640                                                 last_char = *c;
1641                                                 current_value += *c;
1642                                         }
1643                                 }
1644                         }
1645                 }
1646         }
1647
1648         /* Finished parsing the tag, add it to the config hash */
1649         config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1650
1651         return true;
1652 }
1653
1654 bool ServerConfig::DoPipe(const std::string &file)
1655 {
1656         FILE* conf = popen(file.c_str(), "r");
1657         bool ret = false;
1658
1659         if (conf)
1660         {
1661                 ret = LoadConf(conf, file.c_str(), false);
1662                 pclose(conf);
1663         }
1664         else
1665                 errstr << "Couldn't execute: " << file << std::endl;
1666
1667         return ret;
1668 }
1669
1670 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1671 {
1672         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1673 }
1674
1675 bool ServerConfig::DoInclude(const std::string &file, bool allowexeinc)
1676 {
1677         std::string confpath;
1678         std::string newfile;
1679         std::string::size_type pos;
1680
1681         confpath = ServerInstance->ConfigFileName;
1682         newfile = file;
1683
1684         std::replace(newfile.begin(),newfile.end(),'\\','/');
1685         std::replace(confpath.begin(),confpath.end(),'\\','/');
1686
1687         if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1688         {
1689                 if((pos = confpath.rfind("/")) != std::string::npos)
1690                 {
1691                         /* Leaves us with just the path */
1692                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1693                 }
1694                 else
1695                 {
1696                         errstr << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1697                         return false;
1698                 }
1699         }
1700
1701         FILE* conf = fopen(newfile.c_str(), "r");
1702         bool ret = false;
1703
1704         if (conf)
1705         {
1706                 ret = LoadConf(conf, newfile, allowexeinc);
1707                 fclose(conf);
1708         }
1709         else
1710                 errstr << "Couldn't open config file: " << file << std::endl;
1711
1712         return ret;
1713 }
1714
1715 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1716 {
1717         return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1718 }
1719
1720 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1721 {
1722         std::string value;
1723         bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1724         strlcpy(result, value.c_str(), length);
1725         return r;
1726 }
1727
1728 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1729 {
1730         return ConfValue(tag, var, "", index, result, allow_linefeeds);
1731 }
1732
1733 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1734 {
1735         ConfigDataHash::size_type pos = index;
1736         if (pos < config_data.count(tag))
1737         {
1738                 ConfigDataHash::iterator iter = config_data.find(tag);
1739
1740                 for(int i = 0; i < index; i++)
1741                         iter++;
1742
1743                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1744                 {
1745                         if(j->first == var)
1746                         {
1747                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1748                                 {
1749                                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1750                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1751                                                 if (*n == '\n')
1752                                                         *n = ' ';
1753                                 }
1754                                 else
1755                                 {
1756                                         result = j->second;
1757                                         return true;
1758                                 }
1759                         }
1760                 }
1761                 if (!default_value.empty())
1762                 {
1763                         result = default_value;
1764                         return true;
1765                 }
1766         }
1767         else if (pos == 0)
1768         {
1769                 if (!default_value.empty())
1770                 {
1771                         result = default_value;
1772                         return true;
1773                 }
1774         }
1775         return false;
1776 }
1777
1778 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1779 {
1780         return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1781 }
1782
1783 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1784 {
1785         return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1786 }
1787
1788 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1789 {
1790         return ConfValueInteger(tag, var, "", index, result);
1791 }
1792
1793 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1794 {
1795         std::string value;
1796         std::istringstream stream;
1797         bool r = ConfValue(tag, var, default_value, index, value);
1798         stream.str(value);
1799         if(!(stream >> result))
1800                 return false;
1801         else
1802         {
1803                 if (!value.empty())
1804                 {
1805                         if (value.substr(0,2) == "0x")
1806                         {
1807                                 char* endptr;
1808
1809                                 value.erase(0,2);
1810                                 result = strtol(value.c_str(), &endptr, 16);
1811
1812                                 /* No digits found */
1813                                 if (endptr == value.c_str())
1814                                         return false;
1815                         }
1816                         else
1817                         {
1818                                 char denominator = *(value.end() - 1);
1819                                 switch (toupper(denominator))
1820                                 {
1821                                         case 'K':
1822                                                 /* Kilobytes -> bytes */
1823                                                 result = result * 1024;
1824                                         break;
1825                                         case 'M':
1826                                                 /* Megabytes -> bytes */
1827                                                 result = result * 1024 * 1024;
1828                                         break;
1829                                         case 'G':
1830                                                 /* Gigabytes -> bytes */
1831                                                 result = result * 1024 * 1024 * 1024;
1832                                         break;
1833                                 }
1834                         }
1835                 }
1836         }
1837         return r;
1838 }
1839
1840
1841 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1842 {
1843         return ConfValueBool(std::string(tag), std::string(var), "", index);
1844 }
1845
1846 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1847 {
1848         return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1849 }
1850
1851 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1852 {
1853         return ConfValueBool(tag, var, "", index);
1854 }
1855
1856 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1857 {
1858         std::string result;
1859         if(!ConfValue(tag, var, default_value, index, result))
1860                 return false;
1861
1862         return ((result == "yes") || (result == "true") || (result == "1"));
1863 }
1864
1865 int ServerConfig::ConfValueEnum(const char* tag)
1866 {
1867         return config_data.count(tag);
1868 }
1869
1870 int ServerConfig::ConfValueEnum(const std::string &tag)
1871 {
1872         return config_data.count(tag);
1873 }
1874
1875 int ServerConfig::ConfVarEnum(const char* tag, int index)
1876 {
1877         return ConfVarEnum(std::string(tag), index);
1878 }
1879
1880 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1881 {
1882         ConfigDataHash::size_type pos = index;
1883
1884         if (pos < config_data.count(tag))
1885         {
1886                 ConfigDataHash::const_iterator iter = config_data.find(tag);
1887
1888                 for(int i = 0; i < index; i++)
1889                         iter++;
1890
1891                 return iter->second.size();
1892         }
1893
1894         return 0;
1895 }
1896
1897 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1898  */
1899 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1900 {
1901         if (!fname || !*fname)
1902                 return false;
1903
1904         FILE* file = NULL;
1905         char linebuf[MAXBUF];
1906
1907         F.clear();
1908
1909         if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1910         {
1911                 std::string::size_type pos;
1912                 std::string confpath = ServerInstance->ConfigFileName;
1913                 std::string newfile = fname;
1914
1915                 if (((pos = confpath.rfind("/"))) != std::string::npos)
1916                         newfile = confpath.substr(0, pos) + std::string("/") + fname;
1917                 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1918                         newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1919
1920                 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1921
1922                 if (!FileExists(newfile.c_str()))
1923                         return false;
1924                 file =  fopen(newfile.c_str(), "r");
1925         }
1926         else
1927         {
1928                 if (!FileExists(fname))
1929                         return false;
1930                 file =  fopen(fname, "r");
1931         }
1932
1933         if (file)
1934         {
1935                 while (!feof(file))
1936                 {
1937                         if (fgets(linebuf, sizeof(linebuf), file))
1938                                 linebuf[strlen(linebuf)-1] = 0;
1939                         else
1940                                 *linebuf = 0;
1941
1942                         F.push_back(*linebuf ? linebuf : " ");
1943                 }
1944
1945                 fclose(file);
1946         }
1947         else
1948                 return false;
1949
1950         return true;
1951 }
1952
1953 bool ServerConfig::FileExists(const char* file)
1954 {
1955         struct stat sb;
1956         if (stat(file, &sb) == -1)
1957                 return false;
1958
1959         if ((sb.st_mode & S_IFDIR) > 0)
1960                 return false;
1961
1962         FILE *input;
1963         if ((input = fopen (file, "r")) == NULL)
1964                 return false;
1965         else
1966         {
1967                 fclose(input);
1968                 return true;
1969         }
1970 }
1971
1972 const char* ServerConfig::CleanFilename(const char* name)
1973 {
1974         const char* p = name + strlen(name);
1975         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1976         return (p != name ? ++p : p);
1977 }
1978
1979
1980 std::string ServerConfig::GetFullProgDir()
1981 {
1982         char buffer[PATH_MAX];
1983 #ifdef WINDOWS
1984         /* Windows has specific api calls to get the exe path that never fail.
1985          * For once, windows has something of use, compared to the POSIX code
1986          * for this, this is positively neato.
1987          */
1988         if (GetModuleFileName(NULL, buffer, MAX_PATH))
1989         {
1990                 std::string fullpath = buffer;
1991                 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1992                 return std::string(fullpath, 0, n);
1993         }
1994 #else
1995         // Get the current working directory
1996         if (getcwd(buffer, PATH_MAX))
1997         {
1998                 std::string remainder = this->argv[0];
1999
2000                 /* Does argv[0] start with /? its a full path, use it */
2001                 if (remainder[0] == '/')
2002                 {
2003                         std::string::size_type n = remainder.rfind("/inspircd");
2004                         return std::string(remainder, 0, n);
2005                 }
2006
2007                 std::string fullpath = std::string(buffer) + "/" + remainder;
2008                 std::string::size_type n = fullpath.rfind("/inspircd");
2009                 return std::string(fullpath, 0, n);
2010         }
2011 #endif
2012         return "/";
2013 }
2014
2015 InspIRCd* ServerConfig::GetInstance()
2016 {
2017         return ServerInstance;
2018 }
2019
2020 std::string ServerConfig::GetSID()
2021 {
2022         return sid;
2023 }
2024
2025 ValueItem::ValueItem(int value)
2026 {
2027         std::stringstream n;
2028         n << value;
2029         v = n.str();
2030 }
2031
2032 ValueItem::ValueItem(bool value)
2033 {
2034         std::stringstream n;
2035         n << value;
2036         v = n.str();
2037 }
2038
2039 void ValueItem::Set(const std::string& value)
2040 {
2041         v = value;
2042 }
2043
2044 void ValueItem::Set(int value)
2045 {
2046         std::stringstream n;
2047         n << value;
2048         v = n.str();
2049 }
2050
2051 int ValueItem::GetInteger()
2052 {
2053         if (v.empty())
2054                 return 0;
2055         return atoi(v.c_str());
2056 }
2057
2058 const char* ValueItem::GetString() const
2059 {
2060         return v.c_str();
2061 }
2062
2063 bool ValueItem::GetBool()
2064 {
2065         return (GetInteger() || v == "yes" || v == "true");
2066 }
2067
2068
2069 void ConfigReaderThread::Run()
2070 {
2071         Config = new ServerConfig(ServerInstance);
2072         Config->Read();
2073         done = true;
2074 }
2075
2076 void ConfigReaderThread::Finish()
2077 {
2078         ServerConfig* old = ServerInstance->Config;
2079         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
2080         ServerInstance->Logs->CloseLogs();
2081         ServerInstance->Config = this->Config;
2082         ServerInstance->Logs->OpenFileLogs();
2083         Config->Apply(old, TheUserUID);
2084
2085         if (Config->valid)
2086         {
2087                 /*
2088                  * Apply the changed configuration from the rehash.
2089                  *
2090                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
2091                  * thoroughly!!!
2092                  */
2093                 ServerInstance->XLines->CheckELines();
2094                 ServerInstance->XLines->CheckELines();
2095                 ServerInstance->XLines->ApplyLines();
2096                 ServerInstance->Res->Rehash();
2097                 ServerInstance->ResetMaxBans();
2098                 Config->ApplyDisabledCommands(Config->DisabledCommands);
2099                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2100                 FOREACH_MOD_I(ServerInstance, I_OnRehash, OnRehash(user));
2101                 ServerInstance->BuildISupport();
2102
2103                 delete old;
2104         }
2105         else
2106         {
2107                 // whoops, abort!
2108                 ServerInstance->Logs->CloseLogs();
2109                 ServerInstance->Config = old;
2110                 ServerInstance->Logs->OpenFileLogs();
2111                 delete this->Config;
2112         }
2113 }
2114
2115 template<>
2116 void ValueContainer<char[MAXBUF]>::Set(ServerConfig* conf, ValueItem const& item)
2117 {
2118         strlcpy(conf->*vptr, item.GetString(), MAXBUF);
2119 }