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