]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Clean up static allocations
[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 InitialConfig::~InitialConfig()
820 {
821         delete val;
822 }
823
824 /* These tags can occur multiple times, and therefore they have special code to read them
825  * which is different to the code for reading the singular tags listed above.
826  */
827 MultiConfig MultiValues[] = {
828
829         {"connect",
830                         {"allow",       "deny",         "password",     "timeout",      "pingfreq",
831                         "sendq",        "recvq",        "localmax",     "globalmax",    "port",
832                         "name",         "parent",       "maxchans",     "limit",        "hash",
833                         NULL},
834                         {"",            "",                             "",                     "",                     "120",
835                          "",            "",                             "3",            "3",            "0",
836                          "",            "",                             "0",        "0",                "",
837                          NULL},
838                         {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR,    DT_INTEGER,     DT_INTEGER,
839                         DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
840                         DT_NOSPACES,    DT_NOSPACES,    DT_INTEGER,     DT_INTEGER,     DT_CHARPTR},
841                         NULL,},
842
843         {"uline",
844                         {"server",      "silent",       NULL},
845                         {"",            "0",            NULL},
846                         {DT_HOSTNAME,   DT_BOOLEAN},
847                         DoULine},
848
849         {"banlist",
850                         {"chan",        "limit",        NULL},
851                         {"",            "",             NULL},
852                         {DT_CHARPTR,    DT_INTEGER},
853                         DoMaxBans},
854
855         {"module",
856                         {"name",        NULL},
857                         {"",            NULL},
858                         {DT_CHARPTR},
859                         NULL},
860
861         {"badip",
862                         {"reason",      "ipmask",       NULL},
863                         {"No reason",   "",             NULL},
864                         {DT_CHARPTR,    DT_IPADDRESS|DT_ALLOW_WILD},
865                         DoZLine},
866
867         {"badnick",
868                         {"reason",      "nick",         NULL},
869                         {"No reason",   "",             NULL},
870                         {DT_CHARPTR,    DT_CHARPTR},
871                         DoQLine},
872
873         {"badhost",
874                         {"reason",      "host",         NULL},
875                         {"No reason",   "",             NULL},
876                         {DT_CHARPTR,    DT_CHARPTR},
877                         DoKLine},
878
879         {"exception",
880                         {"reason",      "host",         NULL},
881                         {"No reason",   "",             NULL},
882                         {DT_CHARPTR,    DT_CHARPTR},
883                         DoELine},
884
885         {"type",
886                         {"name",        "classes",      NULL},
887                         {"",            "",             NULL},
888                         {DT_NOSPACES,   DT_CHARPTR},
889                         DoType},
890
891         {"class",
892                         {"name",        "commands",     "usermodes",    "chanmodes",    "privs",        NULL},
893                         {"",            "",                             "",                             "",                     "",                     NULL},
894                         {DT_NOSPACES,   DT_CHARPTR,     DT_CHARPTR,     DT_CHARPTR, DT_CHARPTR},
895                         DoClass},
896 };
897
898 /* These tags MUST occur and must ONLY occur once in the config file */
899 static const char* Once[] = { "server", "admin", "files", "power", "options" };
900
901 // WARNING: it is not safe to use most of the codebase in this function, as it
902 // will run in the config reader thread
903 void ServerConfig::Read()
904 {
905         /* Load and parse the config file, if there are any errors then explode */
906
907         if (!this->DoInclude(ServerInstance->ConfigFileName, true))
908         {
909                 valid = false;
910                 return;
911         }
912 }
913
914 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
915 {
916         valid = true;
917         /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
918         errstr.clear();
919         errstr.str().clear();
920         include_stack.clear();
921
922         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
923         try
924         {
925                 /* Check we dont have more than one of singular tags, or any of them missing
926                  */
927                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
928                         CheckOnce(Once[Index]);
929
930                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
931                 {
932                         char item[MAXBUF];
933                         *item = 0;
934                         if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
935                                 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
936                 }
937
938                 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
939                  */
940                 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
941                 {
942                         char item[MAXBUF];
943                         int dt = Values[Index].datatype;
944                         bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
945                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
946                         dt &= ~DT_ALLOW_NEWLINE;
947                         dt &= ~DT_ALLOW_WILD;
948
949                         ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
950                         ValueItem vi(item);
951
952                         if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
953                                 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
954
955                         switch (dt)
956                         {
957                                 case DT_NOSPACES:
958                                 {
959                                         ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
960                                         ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
961                                         vcc->Set(this, vi.GetValue());
962                                 }
963                                 break;
964                                 case DT_HOSTNAME:
965                                 {
966                                         ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
967                                         ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
968                                         vcc->Set(this, vi.GetValue());
969                                 }
970                                 break;
971                                 case DT_IPADDRESS:
972                                 {
973                                         ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
974                                         ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
975                                         vcc->Set(this, vi.GetValue());
976                                 }
977                                 break;
978                                 case DT_CHANNEL:
979                                 {
980                                         ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
981                                         if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
982                                         {
983                                                 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
984                                         }
985                                         vcc->Set(this, vi.GetValue());
986                                 }
987                                 break;
988                                 case DT_CHARPTR:
989                                 {
990                                         ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
991                                         if (vcs)
992                                                 vcs->Set(this, vi.GetValue());
993                                 }
994                                 break;
995                                 case DT_INTEGER:
996                                 {
997                                         int val = vi.GetInteger();
998                                         ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
999                                         vci->Set(this, val);
1000                                 }
1001                                 break;
1002                                 case DT_LIMIT:
1003                                 {
1004                                         int val = vi.GetInteger();
1005                                         ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1006                                         vci->Set(this, val);
1007                                 }
1008                                 break;
1009                                 case DT_BOOLEAN:
1010                                 {
1011                                         bool val = vi.GetBool();
1012                                         ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1013                                         vcb->Set(this, val);
1014                                 }
1015                                 break;
1016                         }
1017                 }
1018
1019                 /* Read the multiple-tag items (class tags, connect tags, etc)
1020                  * and call the callbacks associated with them. We have three
1021                  * callbacks for these, a 'start', 'item' and 'end' callback.
1022                  */
1023                 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1024                 {
1025                         int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1026
1027                         for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1028                         {
1029                                 ValueList vl;
1030                                 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1031                                 {
1032                                         int dt = MultiValues[Index].datatype[valuenum];
1033                                         bool allow_newlines =  ((dt & DT_ALLOW_NEWLINE) > 0);
1034                                         bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1035                                         dt &= ~DT_ALLOW_NEWLINE;
1036                                         dt &= ~DT_ALLOW_WILD;
1037
1038                                         switch (dt)
1039                                         {
1040                                                 case DT_NOSPACES:
1041                                                 {
1042                                                         char item[MAXBUF];
1043                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1044                                                                 vl.push_back(ValueItem(item));
1045                                                         else
1046                                                                 vl.push_back(ValueItem(""));
1047                                                         ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1048                                                 }
1049                                                 break;
1050                                                 case DT_HOSTNAME:
1051                                                 {
1052                                                         char item[MAXBUF];
1053                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1054                                                                 vl.push_back(ValueItem(item));
1055                                                         else
1056                                                                 vl.push_back(ValueItem(""));
1057                                                         ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1058                                                 }
1059                                                 break;
1060                                                 case DT_IPADDRESS:
1061                                                 {
1062                                                         char item[MAXBUF];
1063                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1064                                                                 vl.push_back(ValueItem(item));
1065                                                         else
1066                                                                 vl.push_back(ValueItem(""));
1067                                                         ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1068                                                 }
1069                                                 break;
1070                                                 case DT_CHANNEL:
1071                                                 {
1072                                                         char item[MAXBUF];
1073                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1074                                                                 vl.push_back(ValueItem(item));
1075                                                         else
1076                                                                 vl.push_back(ValueItem(""));
1077                                                         if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1078                                                                 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1079                                                 }
1080                                                 break;
1081                                                 case DT_CHARPTR:
1082                                                 {
1083                                                         char item[MAXBUF];
1084                                                         if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1085                                                                 vl.push_back(ValueItem(item));
1086                                                         else
1087                                                                 vl.push_back(ValueItem(""));
1088                                                 }
1089                                                 break;
1090                                                 case DT_INTEGER:
1091                                                 {
1092                                                         int item = 0;
1093                                                         if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1094                                                                 vl.push_back(ValueItem(item));
1095                                                         else
1096                                                                 vl.push_back(ValueItem(0));
1097                                                 }
1098                                                 break;
1099                                                 case DT_BOOLEAN:
1100                                                 {
1101                                                         bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1102                                                         vl.push_back(ValueItem(item));
1103                                                 }
1104                                                 break;
1105                                         }
1106                                 }
1107                                 if (MultiValues[Index].validation_function)
1108                                         MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1109                         }
1110                 }
1111
1112                 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1113                  * rather than assign(str, 0, val + 1)
1114                  */
1115                 Limits.Finalise();
1116
1117                 // Handle special items
1118                 CrossCheckOperClassType();
1119                 CrossCheckConnectBlocks(old);
1120         }
1121         catch (CoreException &ce)
1122         {
1123                 errstr << ce.GetReason();
1124                 valid = false;
1125         }
1126
1127         // write once here, to try it out and make sure its ok
1128         ServerInstance->WritePID(this->PID);
1129
1130         /*
1131          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1132          */
1133         if (old)
1134         {
1135                 this->ServerName = old->ServerName;
1136                 this->sid = old->sid;
1137                 this->argv = old->argv;
1138                 this->argc = old->argc;
1139
1140                 // Same for ports... they're bound later on first run.
1141                 FailedPortList pl;
1142                 ServerInstance->BindPorts(pl);
1143                 if (pl.size())
1144                 {
1145                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1146
1147                         int j = 1;
1148                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1149                         {
1150                                 char buf[MAXBUF];
1151                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1152                                 errstr << buf;
1153                         }
1154                 }
1155         }
1156
1157         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1158
1159         valid = errstr.str().empty();
1160         if (!valid)
1161                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1162
1163         while (errstr.good())
1164         {
1165                 std::string line;
1166                 getline(errstr, line, '\n');
1167                 if (!line.empty())
1168                 {
1169                         if (user)
1170                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1171                         else
1172                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1173                 }
1174
1175                 if (!old)
1176                 {
1177                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1178                         printf("%s\n", line.c_str());
1179                 }
1180         }
1181
1182         errstr.clear();
1183         errstr.str(std::string());
1184
1185         /* No old configuration -> initial boot, nothing more to do here */
1186         if (!old)
1187         {
1188                 if (!valid)
1189                 {
1190                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1191                 }
1192
1193                 return;
1194         }
1195
1196         // If there were errors processing configuration, don't touch modules.
1197         if (!valid)
1198                 return;
1199
1200         ApplyModules(user);
1201 }
1202
1203 void ServerConfig::ApplyModules(User* user)
1204 {
1205         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1206         std::vector<std::string> added_modules;
1207         std::set<std::string> removed_modules(v.begin(), v.end());
1208
1209         int new_module_count = ConfValueEnum("module");
1210         for(int i=0; i < new_module_count; i++)
1211         {
1212                 std::string name;
1213                 if (ConfValue("module", "name", i, name, false))
1214                 {
1215                         // if this module is already loaded, the erase will succeed, so we need do nothing
1216                         // otherwise, we need to add the module (which will be done later)
1217                         if (removed_modules.erase(name) == 0)
1218                                 added_modules.push_back(name);
1219                 }
1220         }
1221
1222         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1223         {
1224                 // Don't remove cmd_*.so, just remove m_*.so
1225                 if (removing->c_str()[0] == 'c')
1226                         continue;
1227                 Module* m = ServerInstance->Modules->Find(*removing);
1228                 if (m && ServerInstance->Modules->Unload(m))
1229                 {
1230                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1231
1232                         if (user)
1233                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1234                         else
1235                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1236                 }
1237                 else
1238                 {
1239                         if (user)
1240                                 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());
1241                         else
1242                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1243                 }
1244         }
1245
1246         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1247         {
1248                 if (ServerInstance->Modules->Load(adding->c_str()))
1249                 {
1250                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1251                         if (user)
1252                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1253                         else
1254                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1255                 }
1256                 else
1257                 {
1258                         if (user)
1259                                 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());
1260                         else
1261                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1262                 }
1263         }
1264
1265         if (user)
1266                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1267         else
1268                 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1269 }
1270
1271 bool ServerConfig::LoadConf(FILE* &conf, const char* filename, bool allowexeinc)
1272 {
1273         std::string line;
1274         char ch;
1275         long linenumber = 1;
1276         long last_successful_parse = 1;
1277         bool in_tag;
1278         bool in_quote;
1279         bool in_comment;
1280         int character_count = 0;
1281
1282         in_tag = false;
1283         in_quote = false;
1284         in_comment = false;
1285
1286         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1287
1288         /* Check if the file open failed first */
1289         if (!conf)
1290         {
1291                 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1292                 return false;
1293         }
1294
1295         for (unsigned int t = 0; t < include_stack.size(); t++)
1296         {
1297                 if (std::string(filename) == include_stack[t])
1298                 {
1299                         errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1300                         return false;
1301                 }
1302         }
1303
1304         /* It's not already included, add it to the list of files we've loaded */
1305         include_stack.push_back(filename);
1306
1307         /* Start reading characters... */
1308         while ((ch = fgetc(conf)) != EOF)
1309         {
1310                 /*
1311                  * Fix for moronic windows issue spotted by Adremelech.
1312                  * Some windows editors save text files as utf-16, which is
1313                  * a total pain in the ass to parse. Users should save in the
1314                  * right config format! If we ever see a file where the first
1315                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1316                  * this is most likely a utf-16 file. Bail out and insult user.
1317                  */
1318                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1319                 {
1320                         errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1321                         return false;
1322                 }
1323
1324                 /*
1325                  * Here we try and get individual tags on separate lines,
1326                  * this would be so easy if we just made people format
1327                  * their config files like that, but they don't so...
1328                  * We check for a '<' and then know the line is over when
1329                  * we get a '>' not inside quotes. If we find two '<' and
1330                  * no '>' then die with an error.
1331                  */
1332
1333                 if ((ch == '#') && !in_quote)
1334                         in_comment = true;
1335
1336                 switch (ch)
1337                 {
1338                         case '\n':
1339                                 if (in_quote)
1340                                         line += '\n';
1341                                 linenumber++;
1342                         case '\r':
1343                                 if (!in_quote)
1344                                         in_comment = false;
1345                         case '\0':
1346                                 continue;
1347                         case '\t':
1348                                 ch = ' ';
1349                 }
1350
1351                 if(in_comment)
1352                         continue;
1353
1354                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1355                  * Note that this WILL NOT usually allow insertion of newlines,
1356                  * because a newline is two characters long. Use it primarily to
1357                  * insert the " symbol.
1358                  *
1359                  * Note that this also involves a further check when parsing the line,
1360                  * which can be found below.
1361                  */
1362                 if ((ch == '\\') && (in_quote) && (in_tag))
1363                 {
1364                         line += ch;
1365                         char real_character;
1366                         if (!feof(conf))
1367                         {
1368                                 real_character = fgetc(conf);
1369                                 if (real_character == 'n')
1370                                         real_character = '\n';
1371                                 line += real_character;
1372                                 continue;
1373                         }
1374                         else
1375                         {
1376                                 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1377                                 return false;
1378                         }
1379                 }
1380
1381                 if (ch != '\r')
1382                         line += ch;
1383
1384                 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1385                 {
1386                         errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1387                         return false;
1388                 }
1389
1390                 if (ch == '<')
1391                 {
1392                         if (in_tag)
1393                         {
1394                                 if (!in_quote)
1395                                 {
1396                                         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;
1397                                         return false;
1398                                 }
1399                         }
1400                         else
1401                         {
1402                                 if (in_quote)
1403                                 {
1404                                         errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1405                                         return false;
1406                                 }
1407                                 else
1408                                 {
1409                                         // errstr << "Opening new config tag on line " << linenumber << std::endl;
1410                                         in_tag = true;
1411                                 }
1412                         }
1413                 }
1414                 else if (ch == '"')
1415                 {
1416                         if (in_tag)
1417                         {
1418                                 if (in_quote)
1419                                 {
1420                                         // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1421                                         in_quote = false;
1422                                 }
1423                                 else
1424                                 {
1425                                         // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1426                                         in_quote = true;
1427                                 }
1428                         }
1429                         else
1430                         {
1431                                 if (in_quote)
1432                                 {
1433                                         errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1434                                 }
1435                                 else
1436                                 {
1437                                         errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1438                                 }
1439                         }
1440                 }
1441                 else if (ch == '>')
1442                 {
1443                         if (!in_quote)
1444                         {
1445                                 if (in_tag)
1446                                 {
1447                                         // errstr << "Closing config tag on line " << linenumber << std::endl;
1448                                         in_tag = false;
1449
1450                                         /*
1451                                          * If this finds an <include> then ParseLine can simply call
1452                                          * LoadConf() and load the included config into the same ConfigDataHash
1453                                          */
1454                                         long bl = linenumber;
1455                                         if (!this->ParseLine(filename, line, linenumber, allowexeinc))
1456                                                 return false;
1457                                         last_successful_parse = linenumber;
1458
1459                                         linenumber = bl;
1460
1461                                         line.clear();
1462                                 }
1463                                 else
1464                                 {
1465                                         errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1466                                         return false;
1467                                 }
1468                         }
1469                 }
1470         }
1471
1472         /* 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 */
1473         if (in_comment || in_quote)
1474         {
1475                 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1476                         is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1477         }
1478
1479         return true;
1480 }
1481
1482
1483 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename, bool allowexeinc)
1484 {
1485         return this->LoadConf(conf, filename.c_str(), allowexeinc);
1486 }
1487
1488 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber, bool allowexeinc)
1489 {
1490         std::string tagname;
1491         std::string current_key;
1492         std::string current_value;
1493         KeyValList results;
1494         char last_char = 0;
1495         bool got_name;
1496         bool got_key;
1497         bool in_quote;
1498
1499         got_name = got_key = in_quote = false;
1500
1501         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1502         {
1503                 if (!got_name)
1504                 {
1505                         /* We don't know the tag name yet. */
1506
1507                         if (*c != ' ')
1508                         {
1509                                 if (*c != '<')
1510                                 {
1511                                         if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1512                                                 tagname += *c;
1513                                         else
1514                                         {
1515                                                 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1516                                                 return false;
1517                                         }
1518                                 }
1519                         }
1520                         else
1521                         {
1522                                 /* We got to a space, we should have the tagname now. */
1523                                 if(tagname.length())
1524                                 {
1525                                         got_name = true;
1526                                 }
1527                         }
1528                 }
1529                 else
1530                 {
1531                         /* We have the tag name */
1532                         if (!got_key)
1533                         {
1534                                 /* We're still reading the key name */
1535                                 if ((*c != '=') && (*c != '>'))
1536                                 {
1537                                         if (*c != ' ')
1538                                         {
1539                                                 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1540                                                         current_key += *c;
1541                                                 else
1542                                                 {
1543                                                         errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1544                                                         return false;
1545                                                 }
1546                                         }
1547                                 }
1548                                 else
1549                                 {
1550                                         /* We got an '=', end of the key name. */
1551                                         got_key = true;
1552                                 }
1553                         }
1554                         else
1555                         {
1556                                 /* We have the key name, now we're looking for quotes and the value */
1557
1558                                 /* Correctly handle escaped characters here.
1559                                  * See the XXX'ed section above.
1560                                  */
1561                                 if ((*c == '\\') && (in_quote))
1562                                 {
1563                                         c++;
1564                                         if (*c == 'n')
1565                                                 current_value += '\n';
1566                                         else
1567                                                 current_value += *c;
1568                                         continue;
1569                                 }
1570                                 else if ((*c == '\\') && (!in_quote))
1571                                 {
1572                                         errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1573                                         return false;
1574                                 }
1575                                 else if ((*c == '\n') && (in_quote))
1576                                 {
1577                                         /* Got a 'real' \n, treat it as part of the value */
1578                                         current_value += '\n';
1579                                         continue;
1580                                 }
1581                                 else if ((*c == '\r') && (in_quote))
1582                                 {
1583                                         /* Got a \r, drop it */
1584                                         continue;
1585                                 }
1586
1587                                 if (*c == '"')
1588                                 {
1589                                         if (!in_quote)
1590                                         {
1591                                                 /* We're not already in a quote. */
1592                                                 in_quote = true;
1593                                         }
1594                                         else
1595                                         {
1596                                                 /* Leaving the quotes, we have the current value */
1597                                                 results.push_back(KeyVal(current_key, current_value));
1598
1599                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1600
1601                                                 in_quote = false;
1602                                                 got_key = false;
1603
1604                                                 if ((tagname == "include") && (current_key == "file"))
1605                                                 {
1606                                                         if (!this->DoInclude(current_value, allowexeinc))
1607                                                                 return false;
1608                                                 }
1609                                                 else if ((tagname == "include") && (current_key == "executable"))
1610                                                 {
1611                                                         if (!allowexeinc)
1612                                                         {
1613                                                                 errstr << "Executable includes are not allowed to use <include:executable>\n"
1614                                                                         "This could be an attempt to execute commands from a malicious remote include.\n"
1615                                                                         "If you need multiple levels of remote include, create a script to assemble the "
1616                                                                         "contents locally or include files using <include:file>\n";
1617                                                                 return false;
1618                                                         }
1619
1620                                                         /* Pipe an executable and use its stdout as config data */
1621                                                         if (!this->DoPipe(current_value))
1622                                                                 return false;
1623                                                 }
1624
1625                                                 current_key.clear();
1626                                                 current_value.clear();
1627                                         }
1628                                 }
1629                                 else
1630                                 {
1631                                         if (in_quote)
1632                                         {
1633                                                 last_char = *c;
1634                                                 current_value += *c;
1635                                         }
1636                                 }
1637                         }
1638                 }
1639         }
1640
1641         /* Finished parsing the tag, add it to the config hash */
1642         config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1643
1644         return true;
1645 }
1646
1647 bool ServerConfig::DoPipe(const std::string &file)
1648 {
1649         FILE* conf = popen(file.c_str(), "r");
1650         bool ret = false;
1651
1652         if (conf)
1653         {
1654                 ret = LoadConf(conf, file.c_str(), false);
1655                 pclose(conf);
1656         }
1657         else
1658                 errstr << "Couldn't execute: " << file << std::endl;
1659
1660         return ret;
1661 }
1662
1663 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1664 {
1665         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1666 }
1667
1668 bool ServerConfig::DoInclude(const std::string &file, bool allowexeinc)
1669 {
1670         FILE* conf = fopen(file.c_str(), "r");
1671         bool ret = false;
1672
1673         if (conf)
1674         {
1675                 ret = LoadConf(conf, file, allowexeinc);
1676                 fclose(conf);
1677         }
1678         else
1679                 errstr << "Couldn't open config file: " << file << std::endl;
1680
1681         return ret;
1682 }
1683
1684 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1685 {
1686         return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1687 }
1688
1689 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1690 {
1691         std::string value;
1692         bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1693         strlcpy(result, value.c_str(), length);
1694         return r;
1695 }
1696
1697 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1698 {
1699         return ConfValue(tag, var, "", index, result, allow_linefeeds);
1700 }
1701
1702 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1703 {
1704         ConfigDataHash::size_type pos = index;
1705         if (pos < config_data.count(tag))
1706         {
1707                 ConfigDataHash::iterator iter = config_data.find(tag);
1708
1709                 for(int i = 0; i < index; i++)
1710                         iter++;
1711
1712                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1713                 {
1714                         if(j->first == var)
1715                         {
1716                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1717                                 {
1718                                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1719                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1720                                                 if (*n == '\n')
1721                                                         *n = ' ';
1722                                 }
1723                                 else
1724                                 {
1725                                         result = j->second;
1726                                         return true;
1727                                 }
1728                         }
1729                 }
1730                 if (!default_value.empty())
1731                 {
1732                         result = default_value;
1733                         return true;
1734                 }
1735         }
1736         else if (pos == 0)
1737         {
1738                 if (!default_value.empty())
1739                 {
1740                         result = default_value;
1741                         return true;
1742                 }
1743         }
1744         return false;
1745 }
1746
1747 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1748 {
1749         return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1750 }
1751
1752 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1753 {
1754         return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1755 }
1756
1757 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1758 {
1759         return ConfValueInteger(tag, var, "", index, result);
1760 }
1761
1762 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1763 {
1764         std::string value;
1765         std::istringstream stream;
1766         bool r = ConfValue(tag, var, default_value, index, value);
1767         stream.str(value);
1768         if(!(stream >> result))
1769                 return false;
1770         else
1771         {
1772                 if (!value.empty())
1773                 {
1774                         if (value.substr(0,2) == "0x")
1775                         {
1776                                 char* endptr;
1777
1778                                 value.erase(0,2);
1779                                 result = strtol(value.c_str(), &endptr, 16);
1780
1781                                 /* No digits found */
1782                                 if (endptr == value.c_str())
1783                                         return false;
1784                         }
1785                         else
1786                         {
1787                                 char denominator = *(value.end() - 1);
1788                                 switch (toupper(denominator))
1789                                 {
1790                                         case 'K':
1791                                                 /* Kilobytes -> bytes */
1792                                                 result = result * 1024;
1793                                         break;
1794                                         case 'M':
1795                                                 /* Megabytes -> bytes */
1796                                                 result = result * 1024 * 1024;
1797                                         break;
1798                                         case 'G':
1799                                                 /* Gigabytes -> bytes */
1800                                                 result = result * 1024 * 1024 * 1024;
1801                                         break;
1802                                 }
1803                         }
1804                 }
1805         }
1806         return r;
1807 }
1808
1809
1810 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1811 {
1812         return ConfValueBool(std::string(tag), std::string(var), "", index);
1813 }
1814
1815 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1816 {
1817         return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1818 }
1819
1820 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1821 {
1822         return ConfValueBool(tag, var, "", index);
1823 }
1824
1825 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1826 {
1827         std::string result;
1828         if(!ConfValue(tag, var, default_value, index, result))
1829                 return false;
1830
1831         return ((result == "yes") || (result == "true") || (result == "1"));
1832 }
1833
1834 int ServerConfig::ConfValueEnum(const char* tag)
1835 {
1836         return config_data.count(tag);
1837 }
1838
1839 int ServerConfig::ConfValueEnum(const std::string &tag)
1840 {
1841         return config_data.count(tag);
1842 }
1843
1844 int ServerConfig::ConfVarEnum(const char* tag, int index)
1845 {
1846         return ConfVarEnum(std::string(tag), index);
1847 }
1848
1849 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1850 {
1851         ConfigDataHash::size_type pos = index;
1852
1853         if (pos < config_data.count(tag))
1854         {
1855                 ConfigDataHash::const_iterator iter = config_data.find(tag);
1856
1857                 for(int i = 0; i < index; i++)
1858                         iter++;
1859
1860                 return iter->second.size();
1861         }
1862
1863         return 0;
1864 }
1865
1866 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1867  */
1868 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1869 {
1870         if (!fname || !*fname)
1871                 return false;
1872
1873         FILE* file = NULL;
1874         char linebuf[MAXBUF];
1875
1876         F.clear();
1877
1878         if (!FileExists(fname))
1879                 return false;
1880         file = fopen(fname, "r");
1881
1882         if (file)
1883         {
1884                 while (!feof(file))
1885                 {
1886                         if (fgets(linebuf, sizeof(linebuf), file))
1887                                 linebuf[strlen(linebuf)-1] = 0;
1888                         else
1889                                 *linebuf = 0;
1890
1891                         F.push_back(*linebuf ? linebuf : " ");
1892                 }
1893
1894                 fclose(file);
1895         }
1896         else
1897                 return false;
1898
1899         return true;
1900 }
1901
1902 bool ServerConfig::FileExists(const char* file)
1903 {
1904         struct stat sb;
1905         if (stat(file, &sb) == -1)
1906                 return false;
1907
1908         if ((sb.st_mode & S_IFDIR) > 0)
1909                 return false;
1910
1911         FILE *input = fopen(file, "r");
1912         if (input == NULL)
1913                 return false;
1914         else
1915         {
1916                 fclose(input);
1917                 return true;
1918         }
1919 }
1920
1921 const char* ServerConfig::CleanFilename(const char* name)
1922 {
1923         const char* p = name + strlen(name);
1924         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1925         return (p != name ? ++p : p);
1926 }
1927
1928
1929 std::string ServerConfig::GetSID()
1930 {
1931         return sid;
1932 }
1933
1934 ValueItem::ValueItem(int value)
1935 {
1936         std::stringstream n;
1937         n << value;
1938         v = n.str();
1939 }
1940
1941 ValueItem::ValueItem(bool value)
1942 {
1943         std::stringstream n;
1944         n << value;
1945         v = n.str();
1946 }
1947
1948 void ValueItem::Set(const std::string& value)
1949 {
1950         v = value;
1951 }
1952
1953 void ValueItem::Set(int value)
1954 {
1955         std::stringstream n;
1956         n << value;
1957         v = n.str();
1958 }
1959
1960 int ValueItem::GetInteger()
1961 {
1962         if (v.empty())
1963                 return 0;
1964         return atoi(v.c_str());
1965 }
1966
1967 const char* ValueItem::GetString() const
1968 {
1969         return v.c_str();
1970 }
1971
1972 bool ValueItem::GetBool()
1973 {
1974         return (GetInteger() || v == "yes" || v == "true");
1975 }
1976
1977
1978 void ConfigReaderThread::Run()
1979 {
1980         Config = new ServerConfig;
1981         Config->Read();
1982         done = true;
1983 }
1984
1985 void ConfigReaderThread::Finish()
1986 {
1987         ServerConfig* old = ServerInstance->Config;
1988         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1989         ServerInstance->Logs->CloseLogs();
1990         ServerInstance->Config = this->Config;
1991         ServerInstance->Logs->OpenFileLogs();
1992         Config->Apply(old, TheUserUID);
1993
1994         if (Config->valid)
1995         {
1996                 /*
1997                  * Apply the changed configuration from the rehash.
1998                  *
1999                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
2000                  * thoroughly!!!
2001                  */
2002                 ServerInstance->XLines->CheckELines();
2003                 ServerInstance->XLines->CheckELines();
2004                 ServerInstance->XLines->ApplyLines();
2005                 ServerInstance->Res->Rehash();
2006                 ServerInstance->ResetMaxBans();
2007                 Config->ApplyDisabledCommands(Config->DisabledCommands);
2008                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2009                 FOREACH_MOD(I_OnRehash, OnRehash(user));
2010                 ServerInstance->BuildISupport();
2011
2012                 delete old;
2013         }
2014         else
2015         {
2016                 // whoops, abort!
2017                 ServerInstance->Logs->CloseLogs();
2018                 ServerInstance->Config = old;
2019                 ServerInstance->Logs->OpenFileLogs();
2020                 delete this->Config;
2021         }
2022 }