2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2006-2009 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "exitcodes.h"
29 #include "configparser.h"
32 ServerLimits::ServerLimits(ConfigTag* tag)
33 : NickMax(tag->getUInt("maxnick", 30))
34 , ChanMax(tag->getUInt("maxchan", 64))
35 , MaxModes(tag->getUInt("maxmodes", 20))
36 , IdentMax(tag->getUInt("maxident", 10))
37 , MaxQuit(tag->getUInt("maxquit", 255))
38 , MaxTopic(tag->getUInt("maxtopic", 307))
39 , MaxKick(tag->getUInt("maxkick", 255))
40 , MaxReal(tag->getUInt("maxreal", tag->getUInt("maxgecos", 128)))
41 , MaxAway(tag->getUInt("maxaway", 200))
42 , MaxLine(tag->getUInt("maxline", 512))
43 , MaxHost(tag->getUInt("maxhost", 64))
47 ServerConfig::ServerPaths::ServerPaths(ConfigTag* tag)
48 : Config(tag->getString("configdir", INSPIRCD_CONFIG_PATH))
49 , Data(tag->getString("datadir", INSPIRCD_DATA_PATH))
50 , Log(tag->getString("logdir", INSPIRCD_LOG_PATH))
51 , Module(tag->getString("moduledir", INSPIRCD_MODULE_PATH))
55 static ConfigTag* CreateEmptyTag()
58 return ConfigTag::create("empty", "<auto>", 0, items);
61 ServerConfig::ServerConfig()
62 : EmptyTag(CreateEmptyTag())
66 , NoSnoticeStack(false)
70 ServerConfig::~ServerConfig()
75 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
77 insp::flat_set<std::string> configlines;
79 ConfigTagList tags = conf->ConfTags(tag);
80 for(ConfigIter i = tags.first; i != tags.second; ++i)
82 ConfigTag* ctag = i->second;
84 if (!ctag->readString(key, mask))
85 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
86 std::string reason = ctag->getString("reason", "<Config>");
87 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
88 xl->from_config = true;
89 configlines.insert(xl->Displayable());
90 if (!ServerInstance->XLines->AddLine(xl, NULL))
94 ServerInstance->XLines->ExpireRemovedConfigLines(make->GetType(), configlines);
97 typedef std::map<std::string, ConfigTag*> LocalIndex;
98 void ServerConfig::CrossCheckOperClassType()
100 LocalIndex operclass;
101 ConfigTagList tags = ConfTags("class");
102 for(ConfigIter i = tags.first; i != tags.second; ++i)
104 ConfigTag* tag = i->second;
105 std::string name = tag->getString("name");
107 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
108 if (operclass.find(name) != operclass.end())
109 throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
110 operclass[name] = tag;
112 tags = ConfTags("type");
113 for(ConfigIter i = tags.first; i != tags.second; ++i)
115 ConfigTag* tag = i->second;
116 std::string name = tag->getString("name");
118 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
119 if (OperTypes.find(name) != OperTypes.end())
120 throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
122 OperInfo* ifo = new OperInfo(name);
123 OperTypes[name] = ifo;
124 ifo->type_block = tag;
126 std::string classname;
127 irc::spacesepstream str(tag->getString("classes"));
128 while (str.GetToken(classname))
130 LocalIndex::iterator cls = operclass.find(classname);
131 if (cls == operclass.end())
132 throw CoreException("Oper type " + name + " has missing class " + classname);
133 ifo->class_blocks.push_back(cls->second);
137 tags = ConfTags("oper");
138 for(ConfigIter i = tags.first; i != tags.second; ++i)
140 ConfigTag* tag = i->second;
142 std::string name = tag->getString("name");
144 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
146 std::string type = tag->getString("type");
147 OperIndex::iterator tblk = OperTypes.find(type);
148 if (tblk == OperTypes.end())
149 throw CoreException("Oper block " + name + " has missing type " + type);
150 if (oper_blocks.find(name) != oper_blocks.end())
151 throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
153 OperInfo* ifo = new OperInfo(type);
154 ifo->oper_block = tag;
155 ifo->type_block = tblk->second->type_block;
156 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
157 oper_blocks[name] = ifo;
161 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
163 typedef std::map<std::string, ConnectClass*> ClassMap;
164 ClassMap oldBlocksByMask;
167 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
169 ConnectClass* c = *i;
170 if (c->name.compare(0, 8, "unnamed-", 8))
172 oldBlocksByMask["n" + c->name] = c;
174 else if (c->type == CC_ALLOW || c->type == CC_DENY)
176 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
178 oldBlocksByMask[typeMask] = c;
183 size_t blk_count = config_data.count("connect");
186 // No connect blocks found; make a trivial default block
188 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
189 (*items)["allow"] = "*";
190 config_data.insert(std::make_pair("connect", tag));
194 Classes.resize(blk_count);
195 std::map<std::string, size_t> names;
197 bool try_again = true;
198 for(size_t tries = 0; try_again; tries++)
201 ConfigTagList tags = ConfTags("connect");
203 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
205 ConfigTag* tag = it->second;
209 ConnectClass* parent = NULL;
210 std::string parentName = tag->getString("parent");
211 if (!parentName.empty())
213 std::map<std::string, size_t>::const_iterator parentIter = names.find(parentName);
214 if (parentIter == names.end())
217 // couldn't find parent this time. If it's the last time, we'll never find it.
218 if (tries >= blk_count)
219 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
222 parent = Classes[parentIter->second];
225 std::string name = tag->getString("name");
226 std::string mask, typeMask;
229 if (tag->readString("allow", mask, false))
232 typeMask = 'a' + mask;
234 else if (tag->readString("deny", mask, false))
237 typeMask = 'd' + mask;
239 else if (!name.empty())
243 typeMask = 'n' + mask;
247 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
252 name = "unnamed-" + ConvToStr(i);
256 typeMask = 'n' + name;
259 if (names.find(name) != names.end())
260 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
263 ConnectClass* me = parent ?
264 new ConnectClass(tag, type, mask, *parent) :
265 new ConnectClass(tag, type, mask);
269 me->registration_timeout = tag->getDuration("timeout", me->registration_timeout);
270 me->pingtime = tag->getDuration("pingfreq", me->pingtime);
272 if (tag->readString("sendq", sendq))
274 // attempt to guess a good hard/soft sendq from a single value
275 unsigned long value = strtoul(sendq.c_str(), NULL, 10);
277 me->softsendqmax = value / 16;
279 me->softsendqmax = value;
280 me->hardsendqmax = value * 8;
282 me->softsendqmax = tag->getUInt("softsendq", me->softsendqmax);
283 me->hardsendqmax = tag->getUInt("hardsendq", me->hardsendqmax);
284 me->recvqmax = tag->getUInt("recvq", me->recvqmax);
285 me->penaltythreshold = tag->getUInt("threshold", me->penaltythreshold);
286 me->commandrate = tag->getUInt("commandrate", me->commandrate);
287 me->fakelag = tag->getBool("fakelag", me->fakelag);
288 me->maxlocal = tag->getUInt("localmax", me->maxlocal);
289 me->maxglobal = tag->getUInt("globalmax", me->maxglobal);
290 me->maxchans = tag->getUInt("maxchans", me->maxchans);
291 me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
292 me->limit = tag->getUInt("limit", me->limit);
293 me->resolvehostnames = tag->getBool("resolvehostnames", me->resolvehostnames);
295 std::string ports = tag->getString("port");
298 irc::portparser portrange(ports, false);
299 while (int port = portrange.GetToken())
300 me->ports.insert(port);
303 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
304 if (oldMask != oldBlocksByMask.end())
306 ConnectClass* old = oldMask->second;
307 oldBlocksByMask.erase(oldMask);
317 static std::string GetServerName()
321 if (gethostname(hostname, sizeof(hostname)) == 0)
323 std::string name(hostname);
324 if (name.find('.') == std::string::npos)
327 if (name.length() <= ServerInstance->Config->Limits.MaxHost && InspIRCd::IsHost(name))
331 return "irc.example.com";
334 void ServerConfig::Fill()
336 ConfigTag* options = ConfValue("options");
337 ConfigTag* security = ConfValue("security");
338 ConfigTag* server = ConfValue("server");
341 ServerName = server->getString("name", GetServerName(), InspIRCd::IsHost);
343 sid = server->getString("id");
344 if (!sid.empty() && !InspIRCd::IsSID(sid))
345 throw CoreException(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.");
347 CaseMapping = options->getString("casemapping", "rfc1459");
348 if (CaseMapping == "ascii")
349 national_case_insensitive_map = ascii_case_insensitive_map;
350 else if (CaseMapping == "rfc1459")
351 national_case_insensitive_map = rfc_case_insensitive_map;
353 throw CoreException("<options:casemapping> must be set to 'ascii', or 'rfc1459'");
357 std::string name = server->getString("name");
358 if (!name.empty() && name != ServerName)
359 throw CoreException("You must restart to change the server name");
361 std::string nsid = server->getString("id");
362 if (!nsid.empty() && nsid != sid)
363 throw CoreException("You must restart to change the server id");
365 std::string casemapping = options->getString("casemapping");
366 if (!casemapping.empty() && casemapping != CaseMapping)
367 throw CoreException("You must restart to change the server casemapping");
370 SoftLimit = ConfValue("performance")->getUInt("softlimit", (SocketEngine::GetMaxFds() > 0 ? SocketEngine::GetMaxFds() : LONG_MAX), 10);
371 CCOnConnect = ConfValue("performance")->getBool("clonesonconnect", true);
372 MaxConn = ConfValue("performance")->getUInt("somaxconn", SOMAXCONN);
373 TimeSkipWarn = ConfValue("performance")->getDuration("timeskipwarn", 2, 0, 30);
374 XLineMessage = options->getString("xlinemessage", options->getString("moronbanner", "You're banned!"));
375 ServerDesc = server->getString("description", "Configure Me");
376 Network = server->getString("network", "Network");
377 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240, 1024, 65534);
378 CustomVersion = security->getString("customversion");
379 HideBans = security->getBool("hidebans");
380 HideServer = security->getString("hideserver", security->getString("hidewhois"));
381 SyntaxHints = options->getBool("syntaxhints");
382 FullHostInTopic = options->getBool("hostintopic");
383 MaxTargets = security->getUInt("maxtargets", 20, 1, 31);
384 DefaultModes = options->getString("defaultmodes", "not");
385 PID = ConfValue("pid")->getString("file");
386 MaxChans = ConfValue("channels")->getUInt("users", 20);
387 OperMaxChans = ConfValue("channels")->getUInt("opers", 0);
388 c_ipv4_range = ConfValue("cidr")->getUInt("ipv4clone", 32, 1, 32);
389 c_ipv6_range = ConfValue("cidr")->getUInt("ipv6clone", 128, 1, 128);
390 Limits = ServerLimits(ConfValue("limits"));
391 Paths = ServerPaths(ConfValue("path"));
392 NoSnoticeStack = options->getBool("nosnoticestack", false);
394 std::string defbind = options->getString("defaultbind");
395 if (stdalgo::string::equalsci(defbind, "ipv4"))
397 WildcardIPv6 = false;
399 else if (stdalgo::string::equalsci(defbind, "ipv6"))
406 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
408 WildcardIPv6 = false;
410 SocketEngine::Close(socktest);
413 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
414 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
415 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
416 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
418 const std::string restrictbannedusers = options->getString("restrictbannedusers", "yes");
419 if (stdalgo::string::equalsci(restrictbannedusers, "no"))
420 RestrictBannedUsers = ServerConfig::BUT_NORMAL;
421 else if (stdalgo::string::equalsci(restrictbannedusers, "silent"))
422 RestrictBannedUsers = ServerConfig::BUT_RESTRICT_SILENT;
423 else if (stdalgo::string::equalsci(restrictbannedusers, "yes"))
424 RestrictBannedUsers = ServerConfig::BUT_RESTRICT_NOTIFY;
426 throw CoreException(restrictbannedusers + " is an invalid <options:restrictbannedusers> value, at " + options->getTagLocation());
429 // WARNING: it is not safe to use most of the codebase in this function, as it
430 // will run in the config reader thread
431 void ServerConfig::Read()
433 /* Load and parse the config file, if there are any errors then explode */
435 ParseStack stack(this);
438 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
440 catch (CoreException& err)
443 errstr << err.GetReason() << std::endl;
447 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
453 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
455 this->CaseMapping = old->CaseMapping;
456 this->ServerName = old->ServerName;
457 this->sid = old->sid;
458 this->cmdline = old->cmdline;
461 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
464 // Ensure the user has actually edited ther config.
465 ConfigTagList dietags = ConfTags("die");
466 if (dietags.first != dietags.second)
468 errstr << "Your configuration has not been edited correctly!" << std::endl;
469 for (ConfigIter iter = dietags.first; iter != dietags.second; ++iter)
471 ConfigTag* tag = iter->second;
472 const std::string reason = tag->getString("reason", "You left a <die> tag in your config", 1);
473 errstr << reason << " (at " << tag->getTagLocation() << ")" << std::endl;
479 // Handle special items
480 CrossCheckOperClassType();
481 CrossCheckConnectBlocks(old);
483 catch (CoreException &ce)
485 errstr << ce.GetReason() << std::endl;
488 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
489 valid = errstr.str().empty();
491 // write once here, to try it out and make sure its ok
493 ServerInstance->WritePID(this->PID, !old);
495 ConfigTagList binds = ConfTags("bind");
496 if (binds.first == binds.second)
497 errstr << "Possible configuration error: you have not defined any <bind> blocks." << std::endl
498 << "You will need to do this if you want clients to be able to connect!" << std::endl;
502 // On first run, ports are bound later on
504 ServerInstance->BindPorts(pl);
507 errstr << "Not all your client ports could be bound." << std::endl
508 << "The following port(s) failed to bind:" << std::endl;
511 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
513 errstr << j << ".\tAddress: " << i->first.str() << "\tReason: " << strerror(i->second) << std::endl;
518 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
522 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "There were errors in your configuration file:");
526 while (errstr.good())
529 getline(errstr, line, '\n');
532 // On startup, print out to console (still attached at this point)
534 std::cout << line << std::endl;
535 // If a user is rehashing, tell them directly
537 user->WriteRemoteNotice(InspIRCd::Format("*** %s", line.c_str()));
539 ServerInstance->SNO->WriteGlobalSno('a', line);
543 errstr.str(std::string());
545 /* No old configuration -> initial boot, nothing more to do here */
550 ServerInstance->Exit(EXIT_STATUS_CONFIG);
557 // If there were errors processing configuration, don't touch modules.
564 user->WriteRemoteNotice("*** Successfully rehashed server.");
565 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
568 void ServerConfig::ApplyModules(User* user)
570 std::vector<std::string> added_modules;
571 ModuleManager::ModuleMap removed_modules = ServerInstance->Modules->GetModules();
573 ConfigTagList tags = ConfTags("module");
574 for(ConfigIter i = tags.first; i != tags.second; ++i)
576 ConfigTag* tag = i->second;
578 if (tag->readString("name", name))
580 name = ModuleManager::ExpandModName(name);
581 // if this module is already loaded, the erase will succeed, so we need do nothing
582 // otherwise, we need to add the module (which will be done later)
583 if (removed_modules.erase(name) == 0)
584 added_modules.push_back(name);
588 for (ModuleManager::ModuleMap::iterator i = removed_modules.begin(); i != removed_modules.end(); ++i)
590 const std::string& modname = i->first;
591 // Don't remove core_*.so, just remove m_*.so
592 if (InspIRCd::Match(modname, "core_*.so", ascii_case_insensitive_map))
594 if (ServerInstance->Modules->Unload(i->second))
596 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s", modname.c_str());
599 user->WriteNumeric(RPL_UNLOADEDMODULE, modname, InspIRCd::Format("Module %s successfully unloaded.", modname.c_str()));
601 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", modname.c_str());
606 user->WriteNumeric(ERR_CANTUNLOADMODULE, modname, InspIRCd::Format("Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str()));
608 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str());
612 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
614 // Skip modules which are already loaded.
615 if (ServerInstance->Modules->Find(*adding))
618 if (ServerInstance->Modules->Load(*adding))
620 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
622 user->WriteNumeric(RPL_LOADEDMODULE, *adding, InspIRCd::Format("Module %s successfully loaded.", adding->c_str()));
624 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
629 user->WriteNumeric(ERR_CANTLOADMODULE, *adding, InspIRCd::Format("Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str()));
631 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
636 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
638 ConfigTagList found = config_data.equal_range(tag);
639 if (found.first == found.second)
641 ConfigTag* rv = found.first->second;
643 if (found.first != found.second)
644 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
645 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
649 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
651 return config_data.equal_range(tag);
654 std::string ServerConfig::Escape(const std::string& str, bool xml)
657 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
662 escaped += xml ? """ : "\"";
665 escaped += xml ? "&" : "&";
668 escaped += xml ? "\\" : "\\\\";
678 void ConfigReaderThread::Run()
684 void ConfigReaderThread::Finish()
686 ServerConfig* old = ServerInstance->Config;
687 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Switching to new configuration...");
688 ServerInstance->Config = this->Config;
689 Config->Apply(old, TheUserUID);
694 * Apply the changed configuration from the rehash.
696 * XXX: The order of these is IMPORTANT, do not reorder them without testing
699 ServerInstance->Users.RehashCloneCounts();
700 ServerInstance->XLines->CheckELines();
701 ServerInstance->XLines->ApplyLines();
702 User* user = ServerInstance->FindNick(TheUserUID);
704 ConfigStatus status(user);
705 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
706 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
710 ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Rehashing " + i->first);
711 i->second->ReadConfig(status);
713 catch (CoreException& modex)
715 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Exception caught: " + modex.GetReason());
717 user->WriteNotice(i->first + ": " + modex.GetReason());
721 // The description of this server may have changed - update it for WHOIS etc.
722 ServerInstance->FakeClient->server->description = Config->ServerDesc;
724 ServerInstance->ISupport.Build();
726 ServerInstance->Logs->CloseLogs();
727 ServerInstance->Logs->OpenFileLogs();
729 if (Config->RawLog && !old->RawLog)
730 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
737 ServerInstance->Config = old;