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