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 ConfigTagList tags = conf->ConfTags(tag);
78 for(ConfigIter i = tags.first; i != tags.second; ++i)
80 ConfigTag* ctag = i->second;
82 if (!ctag->readString(key, mask))
83 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
84 std::string reason = ctag->getString("reason", "<Config>");
85 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
86 xl->from_config = true;
87 if (!ServerInstance->XLines->AddLine(xl, NULL))
92 typedef std::map<std::string, ConfigTag*> LocalIndex;
93 void ServerConfig::CrossCheckOperClassType()
96 ConfigTagList tags = ConfTags("class");
97 for(ConfigIter i = tags.first; i != tags.second; ++i)
99 ConfigTag* tag = i->second;
100 std::string name = tag->getString("name");
102 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
103 if (operclass.find(name) != operclass.end())
104 throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
105 operclass[name] = tag;
107 tags = ConfTags("type");
108 for(ConfigIter i = tags.first; i != tags.second; ++i)
110 ConfigTag* tag = i->second;
111 std::string name = tag->getString("name");
113 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
114 if (OperTypes.find(name) != OperTypes.end())
115 throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
117 OperInfo* ifo = new OperInfo(name);
118 OperTypes[name] = ifo;
119 ifo->type_block = tag;
121 std::string classname;
122 irc::spacesepstream str(tag->getString("classes"));
123 while (str.GetToken(classname))
125 LocalIndex::iterator cls = operclass.find(classname);
126 if (cls == operclass.end())
127 throw CoreException("Oper type " + name + " has missing class " + classname);
128 ifo->class_blocks.push_back(cls->second);
132 tags = ConfTags("oper");
133 for(ConfigIter i = tags.first; i != tags.second; ++i)
135 ConfigTag* tag = i->second;
137 std::string name = tag->getString("name");
139 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
141 std::string type = tag->getString("type");
142 OperIndex::iterator tblk = OperTypes.find(type);
143 if (tblk == OperTypes.end())
144 throw CoreException("Oper block " + name + " has missing type " + type);
145 if (oper_blocks.find(name) != oper_blocks.end())
146 throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
148 OperInfo* ifo = new OperInfo(type);
149 ifo->oper_block = tag;
150 ifo->type_block = tblk->second->type_block;
151 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
152 oper_blocks[name] = ifo;
156 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
158 typedef std::map<std::string, ConnectClass*> ClassMap;
159 ClassMap oldBlocksByMask;
162 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
164 ConnectClass* c = *i;
165 if (c->name.compare(0, 8, "unnamed-", 8))
167 oldBlocksByMask["n" + c->name] = c;
169 else if (c->type == CC_ALLOW || c->type == CC_DENY)
171 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
173 oldBlocksByMask[typeMask] = c;
178 size_t blk_count = config_data.count("connect");
181 // No connect blocks found; make a trivial default block
183 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
184 (*items)["allow"] = "*";
185 config_data.insert(std::make_pair("connect", tag));
189 Classes.resize(blk_count);
190 std::map<std::string, size_t> names;
192 bool try_again = true;
193 for(size_t tries = 0; try_again; tries++)
196 ConfigTagList tags = ConfTags("connect");
198 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
200 ConfigTag* tag = it->second;
204 ConnectClass* parent = NULL;
205 std::string parentName = tag->getString("parent");
206 if (!parentName.empty())
208 std::map<std::string, size_t>::const_iterator parentIter = names.find(parentName);
209 if (parentIter == names.end())
212 // couldn't find parent this time. If it's the last time, we'll never find it.
213 if (tries >= blk_count)
214 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
217 parent = Classes[parentIter->second];
220 std::string name = tag->getString("name");
221 std::string mask, typeMask;
224 if (tag->readString("allow", mask, false))
227 typeMask = 'a' + mask;
229 else if (tag->readString("deny", mask, false))
232 typeMask = 'd' + mask;
234 else if (!name.empty())
238 typeMask = 'n' + mask;
242 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
247 name = "unnamed-" + ConvToStr(i);
251 typeMask = 'n' + name;
254 if (names.find(name) != names.end())
255 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
258 ConnectClass* me = parent ?
259 new ConnectClass(tag, type, mask, *parent) :
260 new ConnectClass(tag, type, mask);
264 me->registration_timeout = tag->getDuration("timeout", me->registration_timeout);
265 me->pingtime = tag->getDuration("pingfreq", me->pingtime);
267 if (tag->readString("sendq", sendq))
269 // attempt to guess a good hard/soft sendq from a single value
270 unsigned long value = strtoul(sendq.c_str(), NULL, 10);
272 me->softsendqmax = value / 16;
274 me->softsendqmax = value;
275 me->hardsendqmax = value * 8;
277 me->softsendqmax = tag->getUInt("softsendq", me->softsendqmax);
278 me->hardsendqmax = tag->getUInt("hardsendq", me->hardsendqmax);
279 me->recvqmax = tag->getUInt("recvq", me->recvqmax);
280 me->penaltythreshold = tag->getUInt("threshold", me->penaltythreshold);
281 me->commandrate = tag->getUInt("commandrate", me->commandrate);
282 me->fakelag = tag->getBool("fakelag", me->fakelag);
283 me->maxlocal = tag->getUInt("localmax", me->maxlocal);
284 me->maxglobal = tag->getUInt("globalmax", me->maxglobal);
285 me->maxchans = tag->getUInt("maxchans", me->maxchans);
286 me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
287 me->limit = tag->getUInt("limit", me->limit);
288 me->resolvehostnames = tag->getBool("resolvehostnames", me->resolvehostnames);
290 std::string ports = tag->getString("port");
293 irc::portparser portrange(ports, false);
294 while (int port = portrange.GetToken())
295 me->ports.insert(port);
298 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
299 if (oldMask != oldBlocksByMask.end())
301 ConnectClass* old = oldMask->second;
302 oldBlocksByMask.erase(oldMask);
312 void ServerConfig::Fill()
314 ConfigTag* options = ConfValue("options");
315 ConfigTag* security = ConfValue("security");
316 ConfigTag* server = ConfValue("server");
319 ServerName = server->getString("name", "irc.example.com", InspIRCd::IsHost);
321 sid = server->getString("id");
322 if (!sid.empty() && !InspIRCd::IsSID(sid))
323 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.");
325 CaseMapping = options->getString("casemapping", "rfc1459");
326 if (CaseMapping == "ascii")
327 national_case_insensitive_map = ascii_case_insensitive_map;
328 else if (CaseMapping == "rfc1459")
329 national_case_insensitive_map = rfc_case_insensitive_map;
331 throw CoreException("<options:casemapping> must be set to 'ascii', or 'rfc1459'");
335 std::string name = server->getString("name");
336 if (!name.empty() && name != ServerName)
337 throw CoreException("You must restart to change the server name");
339 std::string nsid = server->getString("id");
340 if (!nsid.empty() && nsid != sid)
341 throw CoreException("You must restart to change the server id");
343 std::string casemapping = options->getString("casemapping");
344 if (!casemapping.empty() && casemapping != CaseMapping)
345 throw CoreException("You must restart to change the server casemapping");
348 SoftLimit = ConfValue("performance")->getUInt("softlimit", (SocketEngine::GetMaxFds() > 0 ? SocketEngine::GetMaxFds() : LONG_MAX), 10);
349 CCOnConnect = ConfValue("performance")->getBool("clonesonconnect", true);
350 MaxConn = ConfValue("performance")->getUInt("somaxconn", SOMAXCONN);
351 TimeSkipWarn = ConfValue("performance")->getDuration("timeskipwarn", 2, 0, 30);
352 XLineMessage = options->getString("xlinemessage", options->getString("moronbanner", "You're banned!"));
353 ServerDesc = server->getString("description", "Configure Me");
354 Network = server->getString("network", "Network");
355 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240, 1024, 65534);
356 CustomVersion = security->getString("customversion");
357 HideBans = security->getBool("hidebans");
358 HideServer = security->getString("hideserver", security->getString("hidewhois"));
359 SyntaxHints = options->getBool("syntaxhints");
360 FullHostInTopic = options->getBool("hostintopic");
361 MaxTargets = security->getUInt("maxtargets", 20, 1, 31);
362 DefaultModes = options->getString("defaultmodes", "not");
363 PID = ConfValue("pid")->getString("file");
364 MaxChans = ConfValue("channels")->getUInt("users", 20);
365 OperMaxChans = ConfValue("channels")->getUInt("opers", 0);
366 c_ipv4_range = ConfValue("cidr")->getUInt("ipv4clone", 32, 1, 32);
367 c_ipv6_range = ConfValue("cidr")->getUInt("ipv6clone", 128, 1, 128);
368 Limits = ServerLimits(ConfValue("limits"));
369 Paths = ServerPaths(ConfValue("path"));
370 NoSnoticeStack = options->getBool("nosnoticestack", false);
372 std::string defbind = options->getString("defaultbind");
373 if (stdalgo::string::equalsci(defbind, "ipv4"))
375 WildcardIPv6 = false;
377 else if (stdalgo::string::equalsci(defbind, "ipv6"))
384 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
386 WildcardIPv6 = false;
388 SocketEngine::Close(socktest);
391 ServerInstance->XLines->ClearConfigLines();
392 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
393 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
394 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
395 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
397 const std::string restrictbannedusers = options->getString("restrictbannedusers", "yes");
398 if (stdalgo::string::equalsci(restrictbannedusers, "no"))
399 RestrictBannedUsers = ServerConfig::BUT_NORMAL;
400 else if (stdalgo::string::equalsci(restrictbannedusers, "silent"))
401 RestrictBannedUsers = ServerConfig::BUT_RESTRICT_SILENT;
402 else if (stdalgo::string::equalsci(restrictbannedusers, "yes"))
403 RestrictBannedUsers = ServerConfig::BUT_RESTRICT_NOTIFY;
405 throw CoreException(restrictbannedusers + " is an invalid <options:restrictbannedusers> value, at " + options->getTagLocation());
408 // WARNING: it is not safe to use most of the codebase in this function, as it
409 // will run in the config reader thread
410 void ServerConfig::Read()
412 /* Load and parse the config file, if there are any errors then explode */
414 ParseStack stack(this);
417 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
419 catch (CoreException& err)
422 errstr << err.GetReason() << std::endl;
426 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
432 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
434 this->CaseMapping = old->CaseMapping;
435 this->ServerName = old->ServerName;
436 this->sid = old->sid;
437 this->cmdline = old->cmdline;
440 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
443 // Ensure the user has actually edited ther config.
444 ConfigTagList dietags = ConfTags("die");
445 if (dietags.first != dietags.second)
447 errstr << "Your configuration has not been edited correctly!" << std::endl;
448 for (ConfigIter iter = dietags.first; iter != dietags.second; ++iter)
450 ConfigTag* tag = iter->second;
451 const std::string reason = tag->getString("reason", "You left a <die> tag in your config", 1);
452 errstr << reason << " (at " << tag->getTagLocation() << ")" << std::endl;
458 // Handle special items
459 CrossCheckOperClassType();
460 CrossCheckConnectBlocks(old);
462 catch (CoreException &ce)
464 errstr << ce.GetReason() << std::endl;
467 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
468 valid = errstr.str().empty();
470 // write once here, to try it out and make sure its ok
472 ServerInstance->WritePID(this->PID, !old);
474 ConfigTagList binds = ConfTags("bind");
475 if (binds.first == binds.second)
476 errstr << "Possible configuration error: you have not defined any <bind> blocks." << std::endl
477 << "You will need to do this if you want clients to be able to connect!" << std::endl;
481 // On first run, ports are bound later on
483 ServerInstance->BindPorts(pl);
486 errstr << "Not all your client ports could be bound." << std::endl
487 << "The following port(s) failed to bind:" << std::endl;
490 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
492 errstr << j << ".\tAddress: " << i->first.str() << "\tReason: " << strerror(i->second) << std::endl;
497 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
501 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "There were errors in your configuration file:");
505 while (errstr.good())
508 getline(errstr, line, '\n');
511 // On startup, print out to console (still attached at this point)
513 std::cout << line << std::endl;
514 // If a user is rehashing, tell them directly
516 user->WriteRemoteNotice(InspIRCd::Format("*** %s", line.c_str()));
518 ServerInstance->SNO->WriteGlobalSno('a', line);
522 errstr.str(std::string());
524 /* No old configuration -> initial boot, nothing more to do here */
529 ServerInstance->Exit(EXIT_STATUS_CONFIG);
536 // If there were errors processing configuration, don't touch modules.
543 user->WriteRemoteNotice("*** Successfully rehashed server.");
544 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
547 void ServerConfig::ApplyModules(User* user)
549 std::vector<std::string> added_modules;
550 ModuleManager::ModuleMap removed_modules = ServerInstance->Modules->GetModules();
552 ConfigTagList tags = ConfTags("module");
553 for(ConfigIter i = tags.first; i != tags.second; ++i)
555 ConfigTag* tag = i->second;
557 if (tag->readString("name", name))
559 name = ModuleManager::ExpandModName(name);
560 // if this module is already loaded, the erase will succeed, so we need do nothing
561 // otherwise, we need to add the module (which will be done later)
562 if (removed_modules.erase(name) == 0)
563 added_modules.push_back(name);
567 for (ModuleManager::ModuleMap::iterator i = removed_modules.begin(); i != removed_modules.end(); ++i)
569 const std::string& modname = i->first;
570 // Don't remove core_*.so, just remove m_*.so
571 if (InspIRCd::Match(modname, "core_*.so", ascii_case_insensitive_map))
573 if (ServerInstance->Modules->Unload(i->second))
575 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s", modname.c_str());
578 user->WriteNumeric(RPL_UNLOADEDMODULE, modname, InspIRCd::Format("Module %s successfully unloaded.", modname.c_str()));
580 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", modname.c_str());
585 user->WriteNumeric(ERR_CANTUNLOADMODULE, modname, InspIRCd::Format("Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str()));
587 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str());
591 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
593 // Skip modules which are already loaded.
594 if (ServerInstance->Modules->Find(*adding))
597 if (ServerInstance->Modules->Load(*adding))
599 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
601 user->WriteNumeric(RPL_LOADEDMODULE, *adding, InspIRCd::Format("Module %s successfully loaded.", adding->c_str()));
603 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
608 user->WriteNumeric(ERR_CANTLOADMODULE, *adding, InspIRCd::Format("Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str()));
610 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
615 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
617 ConfigTagList found = config_data.equal_range(tag);
618 if (found.first == found.second)
620 ConfigTag* rv = found.first->second;
622 if (found.first != found.second)
623 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
624 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
628 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
630 return config_data.equal_range(tag);
633 std::string ServerConfig::Escape(const std::string& str, bool xml)
636 for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
641 escaped += xml ? """ : "\"";
644 escaped += xml ? "&" : "&";
647 escaped += xml ? "\\" : "\\\\";
657 void ConfigReaderThread::Run()
663 void ConfigReaderThread::Finish()
665 ServerConfig* old = ServerInstance->Config;
666 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Switching to new configuration...");
667 ServerInstance->Config = this->Config;
668 Config->Apply(old, TheUserUID);
673 * Apply the changed configuration from the rehash.
675 * XXX: The order of these is IMPORTANT, do not reorder them without testing
678 ServerInstance->Users.RehashCloneCounts();
679 ServerInstance->XLines->CheckELines();
680 ServerInstance->XLines->ApplyLines();
681 User* user = ServerInstance->FindNick(TheUserUID);
683 ConfigStatus status(user);
684 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
685 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
689 ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Rehashing " + i->first);
690 i->second->ReadConfig(status);
692 catch (CoreException& modex)
694 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Exception caught: " + modex.GetReason());
696 user->WriteNotice(i->first + ": " + modex.GetReason());
700 // The description of this server may have changed - update it for WHOIS etc.
701 ServerInstance->FakeClient->server->description = Config->ServerDesc;
703 ServerInstance->ISupport.Build();
705 ServerInstance->Logs->CloseLogs();
706 ServerInstance->Logs->OpenFileLogs();
708 if (Config->RawLog && !old->RawLog)
709 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
716 ServerInstance->Config = old;