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