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