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