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