]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
df7721e826adfe0d4bc5ac327fc3c318d8b49c0e
[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->Logs->Log("CONFIG", DEFAULT, "Done reading configuration file.");
1153
1154         /* If we're rehashing, let's load any new modules, and unload old ones
1155          */
1156         if (!bail)
1157         {
1158                 int found_ports = 0;
1159                 FailedPortList pl;
1160                 ServerInstance->BindPorts(false, found_ports, pl);
1161
1162                 if (pl.size() && user)
1163                 {
1164                         ServerInstance->Threads->Mutex(true);
1165                         user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
1166                         user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick);
1167                         int j = 1;
1168                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1169                         {
1170                                 user->WriteServ("NOTICE %s :*** %d.   IP: %s     Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
1171                         }
1172                         ServerInstance->Threads->Mutex(false);
1173                 }
1174
1175                 ServerInstance->Threads->Mutex(true);
1176                 if (!removed_modules.empty())
1177                 {
1178                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1179                         {
1180                                 if (ServerInstance->Modules->Unload(removing->c_str()))
1181                                 {
1182                                         ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1183
1184                                         if (user)
1185                                                 user->WriteNumeric(973, "%s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
1186
1187                                         rem++;
1188                                 }
1189                                 else
1190                                 {
1191                                         if (user)
1192                                                 user->WriteNumeric(972, "%s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
1193                                 }
1194                         }
1195                 }
1196
1197                 if (!added_modules.empty())
1198                 {
1199                         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1200                         {
1201                                 if (ServerInstance->Modules->Load(adding->c_str()))
1202                                 {
1203                                         ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH LOADED MODULE: %s",adding->c_str());
1204
1205                                         if (user)
1206                                                 user->WriteNumeric(975, "%s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
1207
1208                                         add++;
1209                                 }
1210                                 else
1211                                 {
1212                                         if (user)
1213                                                 user->WriteNumeric(974, "%s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
1214                                 }
1215                         }
1216                 }
1217
1218                 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());
1219
1220                 ServerInstance->Threads->Mutex(false);
1221
1222         }
1223
1224         /** Note: This is safe, the method checks for user == NULL */
1225         ServerInstance->Threads->Mutex(true);
1226         ServerInstance->Parser->SetupCommandTable(user);
1227         ServerInstance->Threads->Mutex(false);
1228
1229         if (user)
1230                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
1231         else
1232                 ServerInstance->SNO->WriteToSnoMask('A', "*** Successfully rehashed server.");
1233
1234 }
1235
1236
1237 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const char* filename, std::ostringstream &errorstream)
1238 {
1239         std::string line;
1240         char ch;
1241         long linenumber;
1242         bool in_tag;
1243         bool in_quote;
1244         bool in_comment;
1245         int character_count = 0;
1246
1247         linenumber = 1;
1248         in_tag = false;
1249         in_quote = false;
1250         in_comment = false;
1251
1252         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1253
1254         /* Check if the file open failed first */
1255         if (!conf)
1256         {
1257                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1258                 return false;
1259         }
1260
1261         for (unsigned int t = 0; t < include_stack.size(); t++)
1262         {
1263                 if (std::string(filename) == include_stack[t])
1264                 {
1265                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1266                         return false;
1267                 }
1268         }
1269
1270         /* It's not already included, add it to the list of files we've loaded */
1271         include_stack.push_back(filename);
1272
1273         /* Start reading characters... */
1274         while (!feof(conf))
1275         {
1276                 ch = fgetc(conf);
1277                 /*
1278                  * Fix for moronic windows issue spotted by Adremelech.
1279                  * Some windows editors save text files as utf-16, which is
1280                  * a total pain in the ass to parse. Users should save in the
1281                  * right config format! If we ever see a file where the first
1282                  * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1283                  * this is most likely a utf-16 file. Bail out and insult user.
1284                  */
1285                 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1286                 {
1287                         errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1288                         return false;
1289                 }
1290
1291                 /*
1292                  * Here we try and get individual tags on separate lines,
1293                  * this would be so easy if we just made people format
1294                  * their config files like that, but they don't so...
1295                  * We check for a '<' and then know the line is over when
1296                  * we get a '>' not inside quotes. If we find two '<' and
1297                  * no '>' then die with an error.
1298                  */
1299
1300                 if ((ch == '#') && !in_quote)
1301                         in_comment = true;
1302
1303                 switch (ch)
1304                 {
1305                         case '\n':
1306                                 if (in_quote)
1307                                         line += '\n';
1308                                 linenumber++;
1309                         case '\r':
1310                                 if (!in_quote)
1311                                         in_comment = false;
1312                         case '\0':
1313                                 continue;
1314                         case '\t':
1315                                 ch = ' ';
1316                 }
1317
1318                 if(in_comment)
1319                         continue;
1320
1321                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1322                  * Note that this WILL NOT usually allow insertion of newlines,
1323                  * because a newline is two characters long. Use it primarily to
1324                  * insert the " symbol.
1325                  *
1326                  * Note that this also involves a further check when parsing the line,
1327                  * which can be found below.
1328                  */
1329                 if ((ch == '\\') && (in_quote) && (in_tag))
1330                 {
1331                         line += ch;
1332                         char real_character;
1333                         if (!feof(conf))
1334                         {
1335                                 real_character = fgetc(conf);
1336                                 if (real_character == 'n')
1337                                         real_character = '\n';
1338                                 line += real_character;
1339                                 continue;
1340                         }
1341                         else
1342                         {
1343                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1344                                 return false;
1345                         }
1346                 }
1347
1348                 if (ch != '\r')
1349                         line += ch;
1350
1351                 if (ch == '<')
1352                 {
1353                         if (in_tag)
1354                         {
1355                                 if (!in_quote)
1356                                 {
1357                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1358                                         return false;
1359                                 }
1360                         }
1361                         else
1362                         {
1363                                 if (in_quote)
1364                                 {
1365                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1366                                         return false;
1367                                 }
1368                                 else
1369                                 {
1370                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1371                                         in_tag = true;
1372                                 }
1373                         }
1374                 }
1375                 else if (ch == '"')
1376                 {
1377                         if (in_tag)
1378                         {
1379                                 if (in_quote)
1380                                 {
1381                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1382                                         in_quote = false;
1383                                 }
1384                                 else
1385                                 {
1386                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1387                                         in_quote = true;
1388                                 }
1389                         }
1390                         else
1391                         {
1392                                 if (in_quote)
1393                                 {
1394                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1395                                 }
1396                                 else
1397                                 {
1398                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1399                                 }
1400                         }
1401                 }
1402                 else if (ch == '>')
1403                 {
1404                         {
1405                                 if (in_tag)
1406                                 {
1407                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
1408                                         in_tag = false;
1409
1410                                         /*
1411                                          * If this finds an <include> then ParseLine can simply call
1412                                          * LoadConf() and load the included config into the same ConfigDataHash
1413                                          */
1414
1415                                         if (!this->ParseLine(target, line, linenumber, errorstream))
1416                                                 return false;
1417
1418                                         line.clear();
1419                                 }
1420                                 else
1421                                 {
1422                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1423                                         return false;
1424                                 }
1425                         }
1426                 }
1427         }
1428
1429         /* 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 */
1430         if (in_comment || in_quote)
1431         {
1432                 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1433                         is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1434         }
1435
1436         return true;
1437 }
1438
1439
1440 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const std::string &filename, std::ostringstream &errorstream)
1441 {
1442         return this->LoadConf(target, conf, filename.c_str(), errorstream);
1443 }
1444
1445 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream)
1446 {
1447         std::string tagname;
1448         std::string current_key;
1449         std::string current_value;
1450         KeyValList results;
1451         bool got_name;
1452         bool got_key;
1453         bool in_quote;
1454
1455         got_name = got_key = in_quote = false;
1456
1457         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1458         {
1459                 if (!got_name)
1460                 {
1461                         /* We don't know the tag name yet. */
1462
1463                         if (*c != ' ')
1464                         {
1465                                 if (*c != '<')
1466                                 {
1467                                         tagname += *c;
1468                                 }
1469                         }
1470                         else
1471                         {
1472                                 /* We got to a space, we should have the tagname now. */
1473                                 if(tagname.length())
1474                                 {
1475                                         got_name = true;
1476                                 }
1477                         }
1478                 }
1479                 else
1480                 {
1481                         /* We have the tag name */
1482                         if (!got_key)
1483                         {
1484                                 /* We're still reading the key name */
1485                                 if (*c != '=')
1486                                 {
1487                                         if (*c != ' ')
1488                                         {
1489                                                 current_key += *c;
1490                                         }
1491                                 }
1492                                 else
1493                                 {
1494                                         /* We got an '=', end of the key name. */
1495                                         got_key = true;
1496                                 }
1497                         }
1498                         else
1499                         {
1500                                 /* We have the key name, now we're looking for quotes and the value */
1501
1502                                 /* Correctly handle escaped characters here.
1503                                  * See the XXX'ed section above.
1504                                  */
1505                                 if ((*c == '\\') && (in_quote))
1506                                 {
1507                                         c++;
1508                                         if (*c == 'n')
1509                                                 current_value += '\n';
1510                                         else
1511                                                 current_value += *c;
1512                                         continue;
1513                                 }
1514                                 else if ((*c == '\n') && (in_quote))
1515                                 {
1516                                         /* Got a 'real' \n, treat it as part of the value */
1517                                         current_value += '\n';
1518                                         linenumber++;
1519                                         continue;
1520                                 }
1521                                 else if ((*c == '\r') && (in_quote))
1522                                         /* Got a \r, drop it */
1523                                         continue;
1524
1525                                 if (*c == '"')
1526                                 {
1527                                         if (!in_quote)
1528                                         {
1529                                                 /* We're not already in a quote. */
1530                                                 in_quote = true;
1531                                         }
1532                                         else
1533                                         {
1534                                                 /* Leaving the quotes, we have the current value */
1535                                                 results.push_back(KeyVal(current_key, current_value));
1536
1537                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1538
1539                                                 in_quote = false;
1540                                                 got_key = false;
1541
1542                                                 if ((tagname == "include") && (current_key == "file"))
1543                                                 {       
1544                                                         if (!this->DoInclude(target, current_value, errorstream))
1545                                                                 return false;
1546                                                 }
1547                                                 else if ((tagname == "include") && (current_key == "executable"))
1548                                                 {
1549                                                         /* Pipe an executable and use its stdout as config data */
1550                                                         if (!this->DoPipe(target, current_value, errorstream))
1551                                                                 return false;
1552                                                 }
1553
1554                                                 current_key.clear();
1555                                                 current_value.clear();
1556                                         }
1557                                 }
1558                                 else
1559                                 {
1560                                         if (in_quote)
1561                                         {
1562                                                 current_value += *c;
1563                                         }
1564                                 }
1565                         }
1566                 }
1567         }
1568
1569         /* Finished parsing the tag, add it to the config hash */
1570         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1571
1572         return true;
1573 }
1574
1575 bool ServerConfig::DoPipe(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1576 {
1577         FILE* conf = popen(file.c_str(), "r");
1578         bool ret = false;
1579
1580         if (conf)
1581         {
1582                 ret = LoadConf(target, conf, file.c_str(), errorstream);
1583                 pclose(conf);
1584         }
1585         else
1586                 errorstream << "Couldn't execute: " << file << std::endl;
1587
1588         return ret;
1589 }
1590
1591 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1592 {
1593         std::string confpath;
1594         std::string newfile;
1595         std::string::size_type pos;
1596
1597         confpath = ServerInstance->ConfigFileName;
1598         newfile = file;
1599
1600         std::replace(newfile.begin(),newfile.end(),'\\','/');
1601         std::replace(confpath.begin(),confpath.end(),'\\','/');
1602
1603         if ((newfile[0] != '/') && (newfile.find("://") == std::string::npos))
1604         {
1605                 if((pos = confpath.rfind("/")) != std::string::npos)
1606                 {
1607                         /* Leaves us with just the path */
1608                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1609                 }
1610                 else
1611                 {
1612                         errorstream << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1613                         return false;
1614                 }
1615         }
1616
1617         FILE* conf = fopen(newfile.c_str(), "r");
1618         bool ret = false;
1619
1620         if (conf)
1621         {
1622                 ret = LoadConf(target, conf, newfile, errorstream);
1623                 fclose(conf);
1624         }
1625         else
1626                 errorstream << "Couldn't open config file: " << file << std::endl;
1627
1628         return ret;
1629 }
1630
1631 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1632 {
1633         return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1634 }
1635
1636 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1637 {
1638         std::string value;
1639         bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1640         strlcpy(result, value.c_str(), length);
1641         return r;
1642 }
1643
1644 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1645 {
1646         return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1647 }
1648
1649 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)
1650 {
1651         ConfigDataHash::size_type pos = index;
1652         if (pos < target.count(tag))
1653         {
1654                 ConfigDataHash::iterator iter = target.find(tag);
1655
1656                 for(int i = 0; i < index; i++)
1657                         iter++;
1658
1659                 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1660                 {
1661                         if(j->first == var)
1662                         {
1663                                 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1664                                 {
1665                                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1666                                         for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1667                                                 if (*n == '\n')
1668                                                         *n = ' ';
1669                                 }
1670                                 else
1671                                 {
1672                                         result = j->second;
1673                                         return true;
1674                                 }
1675                         }
1676                 }
1677                 if (!default_value.empty())
1678                 {
1679                         result = default_value;
1680                         return true;
1681                 }
1682         }
1683         else if(pos == 0)
1684         {
1685                 if (!default_value.empty())
1686                 {
1687                         result = default_value;
1688                         return true;
1689                 }
1690         }
1691         return false;
1692 }
1693
1694 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1695 {
1696         return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1697 }
1698
1699 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1700 {
1701         return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1702 }
1703
1704 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1705 {
1706         return ConfValueInteger(target, tag, var, "", index, result);
1707 }
1708
1709 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1710 {
1711         std::string value;
1712         std::istringstream stream;
1713         bool r = ConfValue(target, tag, var, default_value, index, value);
1714         stream.str(value);
1715         if(!(stream >> result))
1716                 return false;
1717         else
1718         {
1719                 if (!value.empty())
1720                 {
1721                         if (value.substr(0,2) == "0x")
1722                         {
1723                                 char* endptr;
1724
1725                                 value.erase(0,2);
1726                                 result = strtol(value.c_str(), &endptr, 16);
1727
1728                                 /* No digits found */
1729                                 if (endptr == value.c_str())
1730                                         return false;
1731                         }
1732                         else
1733                         {
1734                                 char denominator = *(value.end() - 1);
1735                                 switch (toupper(denominator))
1736                                 {
1737                                         case 'K':
1738                                                 /* Kilobytes -> bytes */
1739                                                 result = result * 1024;
1740                                         break;
1741                                         case 'M':
1742                                                 /* Megabytes -> bytes */
1743                                                 result = result * 1024 * 1024;
1744                                         break;
1745                                         case 'G':
1746                                                 /* Gigabytes -> bytes */
1747                                                 result = result * 1024 * 1024 * 1024;
1748                                         break;
1749                                 }
1750                         }
1751                 }
1752         }
1753         return r;
1754 }
1755
1756
1757 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1758 {
1759         return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1760 }
1761
1762 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1763 {
1764         return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1765 }
1766
1767 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1768 {
1769         return ConfValueBool(target, tag, var, "", index);
1770 }
1771
1772 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1773 {
1774         std::string result;
1775         if(!ConfValue(target, tag, var, default_value, index, result))
1776                 return false;
1777
1778         return ((result == "yes") || (result == "true") || (result == "1"));
1779 }
1780
1781 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1782 {
1783         return target.count(tag);
1784 }
1785
1786 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1787 {
1788         return target.count(tag);
1789 }
1790
1791 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1792 {
1793         return ConfVarEnum(target, std::string(tag), index);
1794 }
1795
1796 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1797 {
1798         ConfigDataHash::size_type pos = index;
1799
1800         if (pos < target.count(tag))
1801         {
1802                 ConfigDataHash::const_iterator iter = target.find(tag);
1803
1804                 for(int i = 0; i < index; i++)
1805                         iter++;
1806
1807                 return iter->second.size();
1808         }
1809
1810         return 0;
1811 }
1812
1813 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1814  */
1815 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1816 {
1817         if (!fname || !*fname)
1818                 return false;
1819
1820         FILE* file = NULL;
1821         char linebuf[MAXBUF];
1822
1823         F.clear();
1824
1825         if ((*fname != '/') && (*fname != '\\'))
1826         {
1827                 std::string::size_type pos;
1828                 std::string confpath = ServerInstance->ConfigFileName;
1829                 std::string newfile = fname;
1830
1831                 if ((pos = confpath.rfind("/")) != std::string::npos)
1832                         newfile = confpath.substr(0, pos) + std::string("/") + fname;
1833                 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1834                         newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1835
1836                 if (!FileExists(newfile.c_str()))
1837                         return false;
1838                 file =  fopen(newfile.c_str(), "r");
1839         }
1840         else
1841         {
1842                 if (!FileExists(fname))
1843                         return false;
1844                 file =  fopen(fname, "r");
1845         }
1846
1847         if (file)
1848         {
1849                 while (!feof(file))
1850                 {
1851                         if (fgets(linebuf, sizeof(linebuf), file))
1852                                 linebuf[strlen(linebuf)-1] = 0;
1853                         else
1854                                 *linebuf = 0;
1855
1856                         if (!feof(file))
1857                         {
1858                                 F.push_back(*linebuf ? linebuf : " ");
1859                         }
1860                 }
1861
1862                 fclose(file);
1863         }
1864         else
1865                 return false;
1866
1867         return true;
1868 }
1869
1870 bool ServerConfig::FileExists(const char* file)
1871 {
1872         struct stat sb;
1873         if (stat(file, &sb) == -1)
1874                 return false;
1875
1876         if ((sb.st_mode & S_IFDIR) > 0)
1877                 return false;
1878              
1879         FILE *input;
1880         if ((input = fopen (file, "r")) == NULL)
1881                 return false;
1882         else
1883         {
1884                 fclose(input);
1885                 return true;
1886         }
1887 }
1888
1889 char* ServerConfig::CleanFilename(char* name)
1890 {
1891         char* p = name + strlen(name);
1892         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1893         return (p != name ? ++p : p);
1894 }
1895
1896
1897 bool ServerConfig::DirValid(const char* dirandfile)
1898 {
1899 #ifdef WINDOWS
1900         return true;
1901 #endif
1902
1903         char work[1024];
1904         char buffer[1024];
1905         char otherdir[1024];
1906         int p;
1907
1908         strlcpy(work, dirandfile, 1024);
1909         p = strlen(work);
1910
1911         // we just want the dir
1912         while (*work)
1913         {
1914                 if (work[p] == '/')
1915                 {
1916                         work[p] = '\0';
1917                         break;
1918                 }
1919
1920                 work[p--] = '\0';
1921         }
1922
1923         // Get the current working directory
1924         if (getcwd(buffer, 1024 ) == NULL )
1925                 return false;
1926
1927         if (chdir(work) == -1)
1928                 return false;
1929
1930         if (getcwd(otherdir, 1024 ) == NULL )
1931                 return false;
1932
1933         if (chdir(buffer) == -1)
1934                 return false;
1935
1936         size_t t = strlen(work);
1937
1938         if (strlen(otherdir) >= t)
1939         {
1940                 otherdir[t] = '\0';
1941                 if (!strcmp(otherdir,work))
1942                 {
1943                         return true;
1944                 }
1945
1946                 return false;
1947         }
1948         else
1949         {
1950                 return false;
1951         }
1952 }
1953
1954 std::string ServerConfig::GetFullProgDir()
1955 {
1956         char buffer[PATH_MAX+1];
1957 #ifdef WINDOWS
1958         /* Windows has specific api calls to get the exe path that never fail.
1959          * For once, windows has something of use, compared to the POSIX code
1960          * for this, this is positively neato.
1961          */
1962         if (GetModuleFileName(NULL, buffer, MAX_PATH))
1963         {
1964                 std::string fullpath = buffer;
1965                 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1966                 return std::string(fullpath, 0, n);
1967         }
1968 #else
1969         // Get the current working directory
1970         if (getcwd(buffer, PATH_MAX))
1971         {
1972                 std::string remainder = this->argv[0];
1973
1974                 /* Does argv[0] start with /? its a full path, use it */
1975                 if (remainder[0] == '/')
1976                 {
1977                         std::string::size_type n = remainder.rfind("/inspircd");
1978                         return std::string(remainder, 0, n);
1979                 }
1980
1981                 std::string fullpath = std::string(buffer) + "/" + remainder;
1982                 std::string::size_type n = fullpath.rfind("/inspircd");
1983                 return std::string(fullpath, 0, n);
1984         }
1985 #endif
1986         return "/";
1987 }
1988
1989 InspIRCd* ServerConfig::GetInstance()
1990 {
1991         return ServerInstance;
1992 }
1993
1994 std::string ServerConfig::GetSID()
1995 {
1996         return sid;
1997 }
1998
1999 ValueItem::ValueItem(int value)
2000 {
2001         std::stringstream n;
2002         n << value;
2003         v = n.str();
2004 }
2005
2006 ValueItem::ValueItem(bool value)
2007 {
2008         std::stringstream n;
2009         n << value;
2010         v = n.str();
2011 }
2012
2013 ValueItem::ValueItem(const char* value)
2014 {
2015         v = value;
2016 }
2017
2018 void ValueItem::Set(const char* value)
2019 {
2020         v = value;
2021 }
2022
2023 void ValueItem::Set(int value)
2024 {
2025         std::stringstream n;
2026         n << value;
2027         v = n.str();
2028 }
2029
2030 int ValueItem::GetInteger()
2031 {
2032         if (v.empty())
2033                 return 0;
2034         return atoi(v.c_str());
2035 }
2036
2037 char* ValueItem::GetString()
2038 {
2039         return (char*)v.c_str();
2040 }
2041
2042 bool ValueItem::GetBool()
2043 {
2044         return (GetInteger() || v == "yes" || v == "true");
2045 }
2046
2047
2048
2049
2050 /*
2051  * XXX should this be in a class? -- w00t
2052  */
2053 bool InitTypes(ServerConfig* conf, const char*)
2054 {
2055         if (conf->opertypes.size())
2056         {
2057                 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
2058                 {
2059                         if (n->second)
2060                                 delete[] n->second;
2061                 }
2062         }
2063
2064         conf->opertypes.clear();
2065         return true;
2066 }
2067
2068 /*
2069  * XXX should this be in a class? -- w00t
2070  */
2071 bool InitClasses(ServerConfig* conf, const char*)
2072 {
2073         if (conf->operclass.size())
2074         {
2075                 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
2076                 {
2077                         if (n->second.commandlist)
2078                                 delete[] n->second.commandlist;
2079                         if (n->second.cmodelist)
2080                                 delete[] n->second.cmodelist;
2081                         if (n->second.umodelist)
2082                                 delete[] n->second.umodelist;
2083                 }
2084         }
2085
2086         conf->operclass.clear();
2087         return true;
2088 }
2089
2090 /*
2091  * XXX should this be in a class? -- w00t
2092  */
2093 bool DoType(ServerConfig* conf, const char*, char**, ValueList &values, int*)
2094 {
2095         const char* TypeName = values[0].GetString();
2096         const char* Classes = values[1].GetString();
2097
2098         conf->opertypes[TypeName] = strnewdup(Classes);
2099         return true;
2100 }
2101
2102 /*
2103  * XXX should this be in a class? -- w00t
2104  */
2105 bool DoClass(ServerConfig* conf, const char* tag, char**, ValueList &values, int*)
2106 {
2107         const char* ClassName = values[0].GetString();
2108         const char* CommandList = values[1].GetString();
2109         const char* UModeList = values[2].GetString();
2110         const char* CModeList = values[3].GetString();
2111
2112         for (const char* c = UModeList; *c; ++c)
2113         {
2114                 if ((*c < 'A' || *c > 'z') && *c != '*')
2115                 {
2116                         throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
2117                 }
2118         }
2119         for (const char* c = CModeList; *c; ++c)
2120         {
2121                 if ((*c < 'A' || *c > 'z') && *c != '*')
2122                 {
2123                         throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
2124                 }
2125         }
2126
2127         conf->operclass[ClassName].commandlist = strnewdup(CommandList);
2128         conf->operclass[ClassName].umodelist = strnewdup(UModeList);
2129         conf->operclass[ClassName].cmodelist = strnewdup(CModeList);
2130         return true;
2131 }
2132
2133 /*
2134  * XXX should this be in a class? -- w00t
2135  */
2136 bool DoneClassesAndTypes(ServerConfig*, const char*)
2137 {
2138         return true;
2139 }
2140
2141
2142
2143 bool InitXLine(ServerConfig* conf, const char* tag)
2144 {
2145         return true;
2146 }
2147
2148 bool DoZLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2149 {
2150         const char* reason = values[0].GetString();
2151         const char* ipmask = values[1].GetString();
2152
2153         ZLine* zl = new ZLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
2154         if (!conf->GetInstance()->XLines->AddLine(zl, NULL))
2155                 delete zl;
2156
2157         return true;
2158 }
2159
2160 bool DoQLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2161 {
2162         const char* reason = values[0].GetString();
2163         const char* nick = values[1].GetString();
2164
2165         QLine* ql = new QLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
2166         if (!conf->GetInstance()->XLines->AddLine(ql, NULL))
2167                 delete ql;
2168
2169         return true;
2170 }
2171
2172 bool DoKLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2173 {
2174         const char* reason = values[0].GetString();
2175         const char* host = values[1].GetString();
2176
2177         XLineManager* xlm = conf->GetInstance()->XLines;
2178
2179         IdentHostPair ih = xlm->IdentSplit(host);
2180
2181         KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2182         if (!xlm->AddLine(kl, NULL))
2183                 delete kl;
2184         return true;
2185 }
2186
2187 bool DoELine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2188 {
2189         const char* reason = values[0].GetString();
2190         const char* host = values[1].GetString();
2191
2192         XLineManager* xlm = conf->GetInstance()->XLines;
2193
2194         IdentHostPair ih = xlm->IdentSplit(host);
2195
2196         ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2197         if (!xlm->AddLine(el, NULL))
2198                 delete el;
2199         return true;
2200 }
2201
2202 // this should probably be moved to configreader, but atm it relies on CheckELines above.
2203 bool DoneELine(ServerConfig* conf, const char* tag)
2204 {
2205         for (std::vector<User*>::const_iterator u2 = conf->GetInstance()->Users->local_users.begin(); u2 != conf->GetInstance()->Users->local_users.end(); u2++)
2206         {
2207                 User* u = (User*)(*u2);
2208                 u->exempt = false;
2209         }
2210
2211         conf->GetInstance()->XLines->CheckELines();
2212         return true;
2213 }
2214
2215 void ConfigReaderThread::Run()
2216 {
2217         /* TODO: TheUser may be invalid by the time we get here! Check its validity, or pass a UID would be better */
2218         ServerInstance->Config->Read(do_bail, TheUser);
2219         ServerInstance->Threads->Mutex(true);
2220         this->SetExitFlag();
2221         ServerInstance->Threads->Mutex(false);
2222 }
2223