2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2015 Attila Molnar <attilamolnar@hush.com>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include "modules/reload.h"
22 #include "modules/cap.h"
26 // From IRCv3 capability-negotiation-3.1.
27 ERR_INVALIDCAPCMD = 410
35 static Cap::ManagerImpl* managerimpl;
37 class Cap::ManagerImpl : public Cap::Manager, public ReloadModule::EventListener
39 /** Stores the cap state of a module being reloaded
46 std::vector<std::string> users;
49 : name(cap->GetName())
53 std::vector<Data> caps;
56 typedef insp::flat_map<std::string, Capability*, irc::insensitive_swo> CapMap;
60 Events::ModuleEventProvider& evprov;
62 static bool CanRequest(LocalUser* user, Ext usercaps, Capability* cap, bool adding)
64 const bool hascap = ((usercaps & cap->GetMask()) != 0);
68 return cap->OnRequest(user, adding);
71 Capability::Bit AllocateBit() const
73 Capability::Bit used = 0;
74 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
76 Capability* cap = i->second;
77 used |= cap->GetMask();
80 for (unsigned int i = 0; i < MAX_CAPS; i++)
82 Capability::Bit bit = (1 << i);
86 throw ModuleException("Too many caps");
89 void OnReloadModuleSave(Module* mod, ReloadModule::CustomData& cd) CXX11_OVERRIDE
91 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnReloadModuleSave()");
95 CapModData* capmoddata = new CapModData;
96 cd.add(this, capmoddata);
98 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
100 Capability* cap = i->second;
101 // Only save users of caps that belong to the module being reloaded
102 if (cap->creator != mod)
105 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Module being reloaded implements cap %s, saving cap users", cap->GetName().c_str());
106 capmoddata->caps.push_back(CapModData::Data(cap));
107 CapModData::Data& capdata = capmoddata->caps.back();
109 // Populate list with uuids of users who are using the cap
110 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
111 for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
113 LocalUser* user = *j;
115 capdata.users.push_back(user->uuid);
120 void OnReloadModuleRestore(Module* mod, void* data) CXX11_OVERRIDE
122 CapModData* capmoddata = static_cast<CapModData*>(data);
123 for (std::vector<CapModData::Data>::const_iterator i = capmoddata->caps.begin(); i != capmoddata->caps.end(); ++i)
125 const CapModData::Data& capdata = *i;
126 Capability* cap = ManagerImpl::Find(capdata.name);
129 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s is no longer available after reload", capdata.name.c_str());
133 // Set back the cap for all users who were using it before the reload
134 for (std::vector<std::string>::const_iterator j = capdata.users.begin(); j != capdata.users.end(); ++j)
136 const std::string& uuid = *j;
137 User* user = ServerInstance->FindUUID(uuid);
140 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User %s is gone when trying to restore cap %s", uuid.c_str(), capdata.name.c_str());
144 cap->set(user, true);
151 ManagerImpl(Module* mod, Events::ModuleEventProvider& evprovref)
153 , ReloadModule::EventListener(mod)
162 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
164 Capability* cap = i->second;
169 void AddCap(Cap::Capability* cap) CXX11_OVERRIDE
171 // No-op if the cap is already registered.
172 // This allows modules to call SetActive() on a cap without checking if it's active first.
173 if (cap->IsRegistered())
176 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Registering cap %s", cap->GetName().c_str());
177 cap->bit = AllocateBit();
178 cap->extitem = &capext;
179 caps.insert(std::make_pair(cap->GetName(), cap));
180 ServerInstance->Modules.AddReferent("cap/" + cap->GetName(), cap);
182 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
185 void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
187 // No-op if the cap is not registered, see AddCap() above
188 if (!cap->IsRegistered())
191 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
193 // Fire the event first so modules can still see who is using the cap which is being unregistered
194 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, false));
196 // Turn off the cap for all users
197 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
198 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
200 LocalUser* user = *i;
201 cap->set(user, false);
204 ServerInstance->Modules.DelReferent(cap);
206 caps.erase(cap->GetName());
209 Capability* Find(const std::string& capname) const CXX11_OVERRIDE
211 CapMap::const_iterator it = caps.find(capname);
212 if (it != caps.end())
217 void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
219 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
220 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
223 Protocol GetProtocol(LocalUser* user) const
225 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
228 void Set302Protocol(LocalUser* user)
230 capext.set(user, capext.get(user) | CAP_302_BIT);
233 bool HandleReq(LocalUser* user, const std::string& reqlist)
235 Ext usercaps = capext.get(user);
236 irc::spacesepstream ss(reqlist);
237 for (std::string capname; ss.GetToken(capname); )
239 bool remove = (capname[0] == '-');
241 capname.erase(capname.begin());
243 Capability* cap = ManagerImpl::Find(capname);
244 if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
248 usercaps = cap->DelFromMask(usercaps);
250 usercaps = cap->AddToMask(usercaps);
253 capext.set(user, usercaps);
257 void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
259 Ext show_caps = (show_all ? ~0 : capext.get(user));
261 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
263 Capability* cap = i->second;
264 if (!(show_caps & cap->GetMask()))
267 if ((show_all) && (!cap->OnList(user)))
272 out.append(cap->GetName());
276 const std::string* capvalue = cap->GetValue(user);
277 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
280 out.append(*capvalue, 0, MAX_VALUE_LENGTH);
287 void HandleClear(LocalUser* user, std::string& result)
289 HandleList(result, user, false, false, true);
294 Cap::ExtItem::ExtItem(Module* mod)
295 : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
299 std::string Cap::ExtItem::serialize(SerializeFormat format, const Extensible* container, void* item) const
302 // XXX: Cast away the const because IS_LOCAL() doesn't handle it
303 LocalUser* user = IS_LOCAL(const_cast<User*>(static_cast<const User*>(container)));
304 if ((format == FORMAT_NETWORK) || (!user))
307 // List requested caps
308 managerimpl->HandleList(ret, user, false, false);
310 // Serialize cap protocol version. If building a human-readable string append a new token, otherwise append only a single character indicating the version.
311 Protocol protocol = managerimpl->GetProtocol(user);
312 if (format == FORMAT_USER)
313 ret.append("capversion=3.");
314 else if (!ret.empty())
315 ret.erase(ret.length()-1);
317 if (protocol == CAP_302)
325 void Cap::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
327 if (format == FORMAT_NETWORK)
330 LocalUser* user = IS_LOCAL(static_cast<User*>(container));
332 return; // Can't happen
334 // Process the cap protocol version which is a single character at the end of the serialized string
335 const char verchar = *value.rbegin();
337 managerimpl->Set302Protocol(user);
339 // Remove the version indicator from the string passed to HandleReq
340 std::string caplist(value, 0, value.size()-1);
341 managerimpl->HandleReq(user, caplist);
344 class CapMessage : public Cap::MessageBase
347 CapMessage(LocalUser* user, const std::string& subcmd, const std::string& result)
348 : Cap::MessageBase(subcmd)
351 PushParamRef(result);
355 class CommandCap : public SplitCommand
357 Events::ModuleEventProvider evprov;
358 Cap::ManagerImpl manager;
359 ClientProtocol::EventProvider protoevprov;
361 void DisplayResult(LocalUser* user, const std::string& subcmd, std::string& result)
363 if (*result.rbegin() == ' ')
364 result.erase(result.end()-1);
365 DisplayResult2(user, subcmd, result);
368 void DisplayResult2(LocalUser* user, const std::string& subcmd, const std::string& result)
370 CapMessage msg(user, subcmd, result);
371 ClientProtocol::Event ev(protoevprov, msg);
378 CommandCap(Module* mod)
379 : SplitCommand(mod, "CAP", 1)
380 , evprov(mod, "event/cap")
381 , manager(mod, evprov)
382 , protoevprov(mod, name)
383 , holdext("cap_hold", ExtensionItem::EXT_USER, mod)
385 works_before_reg = true;
388 CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
390 if (user->registered != REG_ALL)
391 holdext.set(user, 1);
393 std::string subcommand(parameters[0].length(), ' ');
394 std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper);
396 if (subcommand == "REQ")
398 if (parameters.size() < 2)
401 const std::string replysubcmd = (manager.HandleReq(user, parameters[1]) ? "ACK" : "NAK");
402 DisplayResult2(user, replysubcmd, parameters[1]);
404 else if (subcommand == "END")
408 else if ((subcommand == "LS") || (subcommand == "LIST"))
410 const bool is_ls = (subcommand.length() == 2);
411 if ((is_ls) && (parameters.size() > 1) && (parameters[1] == "302"))
412 manager.Set302Protocol(user);
415 // Show values only if supports v3.2 and doing LS
416 manager.HandleList(result, user, is_ls, ((is_ls) && (manager.GetProtocol(user) != Cap::CAP_LEGACY)));
417 DisplayResult(user, subcommand, result);
419 else if ((subcommand == "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
422 manager.HandleClear(user, result);
423 DisplayResult(user, "ACK", result);
427 user->WriteNumeric(ERR_INVALIDCAPCMD, subcommand.empty() ? "*" : subcommand, "Invalid CAP subcommand");
435 class ModuleCap : public Module
445 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
447 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
450 Version GetVersion() CXX11_OVERRIDE
452 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
456 MODULE_INIT(ModuleCap)