1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
17 #include "exitcodes.h"
18 #include "commands/cmd_whowas.h"
20 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
22 /* Needs forward declaration */
23 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data);
25 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
28 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
29 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
30 *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
31 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = *SuffixQuit = '\0';
32 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
34 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
35 CycleHosts = writelog = AllowHalfop = true;
36 dns_timeout = DieDelay = 5;
38 NetBufferSize = 10240;
39 SoftLimit = MAXCLIENTS;
47 DNSServerValidator = &ValidateDnsServer;
50 void ServerConfig::ClearStack()
52 include_stack.clear();
55 Module* ServerConfig::GetIOHook(int port)
57 std::map<int,Module*>::iterator x = IOHookModule.find(port);
58 return (x != IOHookModule.end() ? x->second : NULL);
61 Module* ServerConfig::GetIOHook(InspSocket* is)
63 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
64 return (x != SocketIOHookModule.end() ? x->second : NULL);
67 bool ServerConfig::AddIOHook(int port, Module* iomod)
71 IOHookModule[port] = iomod;
76 throw ModuleException("Port already hooked by another module");
81 bool ServerConfig::AddIOHook(Module* iomod, InspSocket* is)
85 SocketIOHookModule[is] = iomod;
86 is->IsIOHooked = true;
91 throw ModuleException("InspSocket derived class already hooked by another module");
96 bool ServerConfig::DelIOHook(int port)
98 std::map<int,Module*>::iterator x = IOHookModule.find(port);
99 if (x != IOHookModule.end())
101 IOHookModule.erase(x);
107 bool ServerConfig::DelIOHook(InspSocket* is)
109 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
110 if (x != SocketIOHookModule.end())
112 SocketIOHookModule.erase(x);
118 void ServerConfig::Update005()
120 std::stringstream out(data005);
123 int token_counter = 0;
127 line5 = line5 + token + " ";
129 if (token_counter >= 13)
132 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
133 isupport.push_back(buf);
141 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
142 isupport.push_back(buf);
146 void ServerConfig::Send005(userrec* user)
148 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
149 user->WriteServ("005 %s %s", user->nick, line->c_str());
152 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
154 int count = ConfValueEnum(this->config_data, tag);
158 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
163 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
169 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
174 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
176 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
178 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
184 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
186 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
188 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
189 data.Set(MAXCLIENTS);
194 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
196 if (data.GetInteger() > SOMAXCONN)
197 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
201 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
203 std::stringstream dcmds(data);
206 /* Enable everything first */
207 for (command_table::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
208 x->second->Disable(false);
210 /* Now disable all the ones which the user wants disabled */
211 while (dcmds >> thiscmd)
213 command_table::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
214 if (cm != ServerInstance->Parser->cmdlist.end())
216 cm->second->Disable(true);
222 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
224 if (!*(data.GetString()))
226 std::string nameserver;
227 // attempt to look up their nameserver from /etc/resolv.conf
228 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
229 ifstream resolv("/etc/resolv.conf");
230 bool found_server = false;
232 if (resolv.is_open())
234 while (resolv >> nameserver)
236 if ((nameserver == "nameserver") && (!found_server))
238 resolv >> nameserver;
239 data.Set(nameserver.c_str());
241 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
247 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
248 data.Set("127.0.0.1");
253 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
254 data.Set("127.0.0.1");
260 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
262 /* If we already have a servername, and they changed it, we should throw an exception. */
263 if ((strcasecmp(conf->ServerName, data.GetString())) && (*conf->ServerName))
265 throw CoreException("Configuration error: You cannot change your servername at runtime! Please restart your server for this change to be applied.");
266 /* XXX: We don't actually reach this return of course... */
269 if (!strchr(data.GetString(),'.'))
271 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
272 std::string moo = std::string(data.GetString()).append(".");
273 data.Set(moo.c_str());
278 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
280 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
282 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
288 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
290 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
292 conf->GetInstance()->Log(DEFAULT,"<options:maxwhoresults> size out of range, setting to default of 128.");
298 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
300 std::string dbg = data.GetString();
301 conf->LogLevel = DEFAULT;
304 conf->LogLevel = DEBUG;
305 else if (dbg == "verbose")
306 conf->LogLevel = VERBOSE;
307 else if (dbg == "default")
308 conf->LogLevel = DEFAULT;
309 else if (dbg == "sparse")
310 conf->LogLevel = SPARSE;
311 else if (dbg == "none")
312 conf->LogLevel = NONE;
314 conf->debugging = (conf->LogLevel == DEBUG);
319 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
321 conf->ReadFile(conf->MOTD, data.GetString());
325 bool ValidateNotEmpty(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
327 if (!*data.GetString())
328 throw CoreException(std::string("The value for ")+tag+" cannot be empty!");
332 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
334 conf->ReadFile(conf->RULES, data.GetString());
338 bool ValidateModeLists(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
340 memset(conf->HideModeLists, 0, 256);
341 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
342 conf->HideModeLists[*x] = true;
346 bool ValidateExemptChanOps(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
348 memset(conf->ExemptChanOps, 0, 256);
349 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
350 conf->ExemptChanOps[*x] = true;
354 bool ValidateInvite(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
356 std::string v = data.GetString();
359 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
361 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
362 else if (v == "dynamic")
363 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
365 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
370 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
372 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
374 if (conf->WhoWasGroupSize < 0)
375 conf->WhoWasGroupSize = 0;
377 if (conf->WhoWasMaxGroups < 0)
378 conf->WhoWasMaxGroups = 0;
380 if (conf->WhoWasMaxKeep < 3600)
382 conf->WhoWasMaxKeep = 3600;
383 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
386 command_t* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
389 std::deque<classbase*> params;
390 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
396 /* Callback called before processing the first <connect> tag
398 bool InitConnect(ServerConfig* conf, const char* tag)
400 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
401 conf->Classes.clear();
405 /* Callback called to process a single <connect> tag
407 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
410 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
411 const char* deny = values[1].GetString();
412 const char* password = values[2].GetString();
413 int timeout = values[3].GetInteger();
414 int pingfreq = values[4].GetInteger();
415 int flood = values[5].GetInteger();
416 int threshold = values[6].GetInteger();
417 int sendq = values[7].GetInteger();
418 int recvq = values[8].GetInteger();
419 int localmax = values[9].GetInteger();
420 int globalmax = values[10].GetInteger();
421 int port = values[11].GetInteger();
422 const char* name = values[12].GetString();
423 const char* parent = values[13].GetString();
424 int maxchans = values[14].GetInteger();
428 /* Find 'parent' and inherit a new class from it,
429 * then overwrite any values that are set here
431 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
433 if (item->GetName() == parent)
435 ConnectClass c(name, *item);
436 c.Update(timeout, flood, *allow ? allow : deny, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port);
437 conf->Classes.push_back(c);
440 throw CoreException("Class name '" + std::string(name) + "' is configured to inherit from class '" + std::string(parent) + "' which cannot be found.");
446 ConnectClass c(name, timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans);
448 conf->Classes.push_back(c);
452 ConnectClass c(name, deny);
454 conf->Classes.push_back(c);
461 /* Callback called when there are no more <connect> tags
463 bool DoneConnect(ServerConfig* conf, const char* tag)
468 /* Callback called before processing the first <uline> tag
470 bool InitULine(ServerConfig* conf, const char* tag)
472 conf->ulines.clear();
476 /* Callback called to process a single <uline> tag
478 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
480 const char* server = values[0].GetString();
481 const bool silent = values[1].GetBool();
482 conf->ulines[server] = silent;
486 /* Callback called when there are no more <uline> tags
488 bool DoneULine(ServerConfig* conf, const char* tag)
493 /* Callback called before processing the first <module> tag
495 bool InitModule(ServerConfig* conf, const char* tag)
497 old_module_names.clear();
498 new_module_names.clear();
499 added_modules.clear();
500 removed_modules.clear();
501 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
503 old_module_names.push_back(*t);
508 /* Callback called to process a single <module> tag
510 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
512 const char* modname = values[0].GetString();
513 new_module_names.push_back(modname);
517 /* Callback called when there are no more <module> tags
519 bool DoneModule(ServerConfig* conf, const char* tag)
521 // now create a list of new modules that are due to be loaded
522 // and a seperate list of modules which are due to be unloaded
523 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
527 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
534 added_modules.push_back(*_new);
537 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
540 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
547 removed_modules.push_back(*oldm);
552 /* Callback called before processing the first <banlist> tag
554 bool InitMaxBans(ServerConfig* conf, const char* tag)
556 conf->maxbans.clear();
560 /* Callback called to process a single <banlist> tag
562 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
564 const char* channel = values[0].GetString();
565 int limit = values[1].GetInteger();
566 conf->maxbans[channel] = limit;
570 /* Callback called when there are no more <banlist> tags.
572 bool DoneMaxBans(ServerConfig* conf, const char* tag)
577 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
579 ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
582 /* Unneeded because of the ServerInstance->Log() aboive? */
583 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
584 ServerInstance->Exit(EXIT_STATUS_CONFIG);
588 std::string errors = errormessage;
589 std::string::size_type start;
590 unsigned int prefixlen;
592 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
595 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
596 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
597 while (start < errors.length())
599 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
600 start += 510 - prefixlen;
605 ServerInstance->WriteOpers("There were errors in the configuration file:");
606 while (start < errors.length())
608 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
616 void ServerConfig::Read(bool bail, userrec* user)
618 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
619 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
620 static char hidemodes[MAXBUF]; /* Modes to not allow listing from users below halfop */
621 static char exemptchanops[MAXBUF]; /* Exempt channel ops from these modes */
622 static char announceinvites[MAXBUF]; /* options:announceinvites setting */
623 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
624 std::ostringstream errstr; /* String stream containing the error output */
626 /* These tags MUST occur and must ONLY occur once in the config file */
627 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
629 /* These tags can occur ONCE or not at all */
630 InitialConfig Values[] = {
631 {"options", "softlimit", MAXCLIENTS_S, new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
632 {"options", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
633 {"options", "moronbanner", "Youre banned!", new ValueContainerChar (this->MoronBanner), DT_CHARPTR, NoValidation},
634 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
635 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
636 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
637 {"admin", "name", "", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
638 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
639 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
640 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
641 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
642 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, ValidateNotEmpty},
643 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
644 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, ValidateNotEmpty},
645 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
646 {"options", "suffixquit", "", new ValueContainerChar (this->SuffixQuit), DT_CHARPTR, NoValidation},
647 {"options", "fixedquit", "", new ValueContainerChar (this->FixedQuit), DT_CHARPTR, NoValidation},
648 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
649 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
650 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
651 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
652 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_CHARPTR, DNSServerValidator},
653 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
654 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
655 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
656 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
657 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
658 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
659 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
660 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
661 {"options", "hidekills", "", new ValueContainerChar (this->HideKillsServer), DT_CHARPTR, NoValidation},
662 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
663 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
664 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
665 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
666 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
667 {"options", "announceinvites", "1", new ValueContainerChar (announceinvites), DT_CHARPTR, ValidateInvite},
668 {"options", "hostintopic", "1", new ValueContainerBool (&this->FullHostInTopic), DT_BOOLEAN, NoValidation},
669 {"options", "hidemodes", "", new ValueContainerChar (hidemodes), DT_CHARPTR, ValidateModeLists},
670 {"options", "exemptchanops","", new ValueContainerChar (exemptchanops), DT_CHARPTR, ValidateExemptChanOps},
671 {"options", "maxtargets", "20", new ValueContainerUInt (&this->MaxTargets), DT_INTEGER, ValidateMaxTargets},
672 {"options", "defaultmodes", "nt", new ValueContainerChar (this->DefaultModes), DT_CHARPTR, NoValidation},
673 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
674 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
675 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
676 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
677 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
678 {"channels", "users", "20", new ValueContainerUInt (&this->MaxChans), DT_INTEGER, NoValidation},
679 {"channels", "opers", "60", new ValueContainerUInt (&this->OperMaxChans), DT_INTEGER, NoValidation},
683 /* These tags can occur multiple times, and therefore they have special code to read them
684 * which is different to the code for reading the singular tags listed above.
686 MultiConfig MultiValues[] = {
689 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
690 "threshold", "sendq", "recvq", "localmax", "globalmax", "port",
691 "name", "parent", "maxchans",
693 {"", "", "", "", "120", "",
694 "", "", "", "3", "3", "0",
697 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
698 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
699 DT_CHARPTR, DT_CHARPTR, DT_INTEGER},
700 InitConnect, DoConnect, DoneConnect},
703 {"server", "silent", NULL},
705 {DT_CHARPTR, DT_BOOLEAN},
706 InitULine,DoULine,DoneULine},
709 {"chan", "limit", NULL},
711 {DT_CHARPTR, DT_INTEGER},
712 InitMaxBans, DoMaxBans, DoneMaxBans},
718 InitModule, DoModule, DoneModule},
721 {"reason", "ipmask", NULL},
722 {"No reason", "", NULL},
723 {DT_CHARPTR, DT_CHARPTR},
724 InitXLine, DoZLine, DoneZLine},
727 {"reason", "nick", NULL},
728 {"No reason", "", NULL},
729 {DT_CHARPTR, DT_CHARPTR},
730 InitXLine, DoQLine, DoneQLine},
733 {"reason", "host", NULL},
734 {"No reason", "", NULL},
735 {DT_CHARPTR, DT_CHARPTR},
736 InitXLine, DoKLine, DoneKLine},
739 {"reason", "host", NULL},
740 {"No reason", "", NULL},
741 {DT_CHARPTR, DT_CHARPTR},
742 InitXLine, DoELine, DoneELine},
745 {"name", "classes", NULL},
747 {DT_CHARPTR, DT_CHARPTR},
748 InitTypes, DoType, DoneClassesAndTypes},
751 {"name", "commands", NULL},
753 {DT_CHARPTR, DT_CHARPTR},
754 InitClasses, DoClass, DoneClassesAndTypes},
759 include_stack.clear();
761 /* Load and parse the config file, if there are any errors then explode */
763 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
764 ConfigDataHash newconfig;
766 if (this->LoadConf(newconfig, ServerInstance->ConfigFileName, errstr))
768 /* If we succeeded, set the ircd config to the new one */
769 this->config_data = newconfig;
773 ReportConfigError(errstr.str(), bail, user);
777 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
780 /* Check we dont have more than one of singular tags, or any of them missing
782 for (int Index = 0; Once[Index]; Index++)
783 if (!CheckOnce(Once[Index], bail, user))
786 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
788 for (int Index = 0; Values[Index].tag; Index++)
791 int dt = Values[Index].datatype;
792 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
793 dt &= ~DT_ALLOW_NEWLINE;
795 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
798 if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
799 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
801 switch (Values[Index].datatype)
805 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
806 /* Make sure we also copy the null terminator */
807 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
812 int val = vi.GetInteger();
813 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
814 vci->Set(&val, sizeof(int));
819 bool val = vi.GetBool();
820 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
821 vcb->Set(&val, sizeof(bool));
825 /* You don't want to know what happens if someones bad code sends us here. */
829 /* We're done with this now */
830 delete Values[Index].val;
833 /* Read the multiple-tag items (class tags, connect tags, etc)
834 * and call the callbacks associated with them. We have three
835 * callbacks for these, a 'start', 'item' and 'end' callback.
837 for (int Index = 0; MultiValues[Index].tag; Index++)
839 MultiValues[Index].init_function(this, MultiValues[Index].tag);
841 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
843 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
846 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
848 int dt = MultiValues[Index].datatype[valuenum];
849 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
850 dt &= ~DT_ALLOW_NEWLINE;
857 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
858 vl.push_back(ValueItem(item));
860 vl.push_back(ValueItem(""));
866 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
867 vl.push_back(ValueItem(item));
869 vl.push_back(ValueItem(0));
874 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
875 vl.push_back(ValueItem(item));
879 /* Someone was smoking craq if we got here, and we're all gonna die. */
884 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
887 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
892 catch (CoreException &ce)
894 ReportConfigError(ce.GetReason(), bail, user);
898 // write once here, to try it out and make sure its ok
899 ServerInstance->WritePID(this->PID);
901 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
903 /* If we're rehashing, let's load any new modules, and unload old ones
909 ServerInstance->BindPorts(false, found_ports, pl);
911 if (pl.size() && user)
913 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
914 user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick);
916 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
918 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
922 if (!removed_modules.empty())
924 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
926 if (ServerInstance->UnloadModule(removing->c_str()))
928 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
931 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
938 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
943 if (!added_modules.empty())
945 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
947 if (ServerInstance->LoadModule(adding->c_str()))
949 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
952 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
959 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
964 ServerInstance->Log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
967 /** Note: This is safe, the method checks for user == NULL */
968 ServerInstance->Parser->SetupCommandTable(user);
971 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
973 ServerInstance->WriteOpers("*** Successfully rehashed server.");
976 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
978 std::ifstream conf(filename);
985 int character_count = 0;
992 /* Check if the file open failed first */
995 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
999 /* Fix the chmod of the file to restrict it to the current user and group */
1000 chmod(filename,0600);
1002 for (unsigned int t = 0; t < include_stack.size(); t++)
1004 if (std::string(filename) == include_stack[t])
1006 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1011 /* It's not already included, add it to the list of files we've loaded */
1012 include_stack.push_back(filename);
1014 /* Start reading characters... */
1015 while (conf.get(ch))
1019 * Fix for moronic windows issue spotted by Adremelech.
1020 * Some windows editors save text files as utf-16, which is
1021 * a total pain in the ass to parse. Users should save in the
1022 * right config format! If we ever see a file where the first
1023 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1024 * this is most likely a utf-16 file. Bail out and insult user.
1026 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1028 errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1033 * Here we try and get individual tags on separate lines,
1034 * this would be so easy if we just made people format
1035 * their config files like that, but they don't so...
1036 * We check for a '<' and then know the line is over when
1037 * we get a '>' not inside quotes. If we find two '<' and
1038 * no '>' then die with an error.
1041 if ((ch == '#') && !in_quote)
1062 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1063 * Note that this WILL NOT usually allow insertion of newlines,
1064 * because a newline is two characters long. Use it primarily to
1065 * insert the " symbol.
1067 * Note that this also involves a further check when parsing the line,
1068 * which can be found below.
1070 if ((ch == '\\') && (in_quote) && (in_tag))
1073 char real_character;
1074 if (conf.get(real_character))
1076 if (real_character == 'n')
1077 real_character = '\n';
1078 line += real_character;
1083 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1097 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1105 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1110 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1121 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1126 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1134 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1138 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1148 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1152 * If this finds an <include> then ParseLine can simply call
1153 * LoadConf() and load the included config into the same ConfigDataHash
1156 if (!this->ParseLine(target, line, linenumber, errorstream))
1163 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1170 /* 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 */
1171 if (in_comment || in_quote)
1173 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1174 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1180 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1182 return this->LoadConf(target, filename.c_str(), errorstream);
1185 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream)
1187 std::string tagname;
1188 std::string current_key;
1189 std::string current_value;
1195 got_name = got_key = in_quote = false;
1197 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1201 /* We don't know the tag name yet. */
1212 /* We got to a space, we should have the tagname now. */
1213 if(tagname.length())
1221 /* We have the tag name */
1224 /* We're still reading the key name */
1234 /* We got an '=', end of the key name. */
1240 /* We have the key name, now we're looking for quotes and the value */
1242 /* Correctly handle escaped characters here.
1243 * See the XXX'ed section above.
1245 if ((*c == '\\') && (in_quote))
1249 current_value += '\n';
1251 current_value += *c;
1254 else if ((*c == '\n') && (in_quote))
1256 /* Got a 'real' \n, treat it as part of the value */
1257 current_value += '\n';
1261 else if ((*c == '\r') && (in_quote))
1262 /* Got a \r, drop it */
1269 /* We're not already in a quote. */
1274 /* Leaving quotes, we have the value */
1275 results.push_back(KeyVal(current_key, current_value));
1277 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1282 if ((tagname == "include") && (current_key == "file"))
1284 if (!this->DoInclude(target, current_value, errorstream))
1288 current_key.clear();
1289 current_value.clear();
1296 current_value += *c;
1303 /* Finished parsing the tag, add it to the config hash */
1304 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1309 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1311 std::string confpath;
1312 std::string newfile;
1313 std::string::size_type pos;
1315 confpath = ServerInstance->ConfigFileName;
1318 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1328 if((pos = confpath.rfind("/")) != std::string::npos)
1330 /* Leaves us with just the path */
1331 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1335 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1340 return LoadConf(target, newfile, errorstream);
1343 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1345 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1348 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1351 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1352 strlcpy(result, value.c_str(), length);
1356 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1358 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1361 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)
1363 ConfigDataHash::size_type pos = index;
1364 if((pos >= 0) && (pos < target.count(tag)))
1366 ConfigDataHash::iterator iter = target.find(tag);
1368 for(int i = 0; i < index; i++)
1371 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1375 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1377 ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1378 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1389 if (!default_value.empty())
1391 result = default_value;
1397 if (!default_value.empty())
1399 result = default_value;
1406 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1408 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1411 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1413 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1416 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1418 return ConfValueInteger(target, tag, var, "", index, result);
1421 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1424 std::istringstream stream;
1425 bool r = ConfValue(target, tag, var, default_value, index, value);
1427 if(!(stream >> result))
1433 if (value.substr(0,2) == "0x")
1438 result = strtol(value.c_str(), &endptr, 16);
1440 /* No digits found */
1441 if (endptr == value.c_str())
1446 char denominator = *(value.end() - 1);
1447 switch (toupper(denominator))
1450 /* Kilobytes -> bytes */
1451 result = result * 1024;
1454 /* Megabytes -> bytes */
1455 result = result * 1024 * 1024;
1458 /* Gigabytes -> bytes */
1459 result = result * 1024 * 1024 * 1024;
1469 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1471 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1474 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1476 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1479 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1481 return ConfValueBool(target, tag, var, "", index);
1484 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1487 if(!ConfValue(target, tag, var, default_value, index, result))
1490 return ((result == "yes") || (result == "true") || (result == "1"));
1493 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1495 return target.count(tag);
1498 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1500 return target.count(tag);
1503 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1505 return ConfVarEnum(target, std::string(tag), index);
1508 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1510 ConfigDataHash::size_type pos = index;
1512 if((pos >= 0) && (pos < target.count(tag)))
1514 ConfigDataHash::const_iterator iter = target.find(tag);
1516 for(int i = 0; i < index; i++)
1519 return iter->second.size();
1525 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1527 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1529 if (!fname || !*fname)
1533 char linebuf[MAXBUF];
1537 if ((*fname != '/') && (*fname != '\\'))
1539 std::string::size_type pos;
1540 std::string confpath = ServerInstance->ConfigFileName;
1541 std::string newfile = fname;
1543 if ((pos = confpath.rfind("/")) != std::string::npos)
1544 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1545 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1546 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1548 if (!FileExists(newfile.c_str()))
1550 file = fopen(newfile.c_str(), "r");
1554 if (!FileExists(fname))
1556 file = fopen(fname, "r");
1563 if (fgets(linebuf, sizeof(linebuf), file))
1564 linebuf[strlen(linebuf)-1] = 0;
1570 F.push_back(*linebuf ? linebuf : " ");
1582 bool ServerConfig::FileExists(const char* file)
1585 if (stat(file, &sb) == -1)
1588 if ((sb.st_mode & S_IFDIR) > 0)
1592 if ((input = fopen (file, "r")) == NULL)
1601 char* ServerConfig::CleanFilename(char* name)
1603 char* p = name + strlen(name);
1604 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1605 return (p != name ? ++p : p);
1609 bool ServerConfig::DirValid(const char* dirandfile)
1617 char otherdir[1024];
1620 strlcpy(work, dirandfile, 1024);
1623 // we just want the dir
1635 // Get the current working directory
1636 if (getcwd(buffer, 1024 ) == NULL )
1639 if (chdir(work) == -1)
1642 if (getcwd(otherdir, 1024 ) == NULL )
1645 if (chdir(buffer) == -1)
1648 size_t t = strlen(work);
1650 if (strlen(otherdir) >= t)
1653 if (!strcmp(otherdir,work))
1666 std::string ServerConfig::GetFullProgDir()
1668 char buffer[PATH_MAX+1];
1670 /* Windows has specific api calls to get the exe path that never fail.
1671 * For once, windows has something of use, compared to the POSIX code
1672 * for this, this is positively neato.
1674 if (GetModuleFileName(NULL, buffer, MAX_PATH))
1676 std::string fullpath = buffer;
1677 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1678 return std::string(fullpath, 0, n);
1681 // Get the current working directory
1682 if (getcwd(buffer, PATH_MAX))
1684 std::string remainder = this->argv[0];
1686 /* Does argv[0] start with /? its a full path, use it */
1687 if (remainder[0] == '/')
1689 std::string::size_type n = remainder.rfind("/inspircd");
1690 return std::string(remainder, 0, n);
1693 std::string fullpath = std::string(buffer) + "/" + remainder;
1694 std::string::size_type n = fullpath.rfind("/inspircd");
1695 return std::string(fullpath, 0, n);
1701 InspIRCd* ServerConfig::GetInstance()
1703 return ServerInstance;
1707 ValueItem::ValueItem(int value)
1709 std::stringstream n;
1714 ValueItem::ValueItem(bool value)
1716 std::stringstream n;
1721 ValueItem::ValueItem(char* value)
1726 void ValueItem::Set(char* value)
1731 void ValueItem::Set(const char* value)
1736 void ValueItem::Set(int value)
1738 std::stringstream n;
1743 int ValueItem::GetInteger()
1747 return atoi(v.c_str());
1750 char* ValueItem::GetString()
1752 return (char*)v.c_str();
1755 bool ValueItem::GetBool()
1757 return (GetInteger() || v == "yes" || v == "true");