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