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