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