2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2018-2019 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2015-2016, 2018 Attila Molnar <attilamolnar@hush.com>
7 * This file is part of InspIRCd. InspIRCd is free software: you can
8 * redistribute it and/or modify it under the terms of the GNU General Public
9 * License as published by the Free Software Foundation, version 2.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "modules/reload.h"
23 #include "modules/cap.h"
27 // From IRCv3 capability-negotiation-3.1.
28 ERR_INVALIDCAPCMD = 410
36 static Cap::ManagerImpl* managerimpl;
38 class Cap::ManagerImpl : public Cap::Manager, public ReloadModule::EventListener
40 /** Stores the cap state of a module being reloaded
47 std::vector<std::string> users;
50 : name(cap->GetName())
54 std::vector<Data> caps;
57 typedef insp::flat_map<std::string, Capability*, irc::insensitive_swo> CapMap;
61 Events::ModuleEventProvider& evprov;
63 static bool CanRequest(LocalUser* user, Ext usercaps, Capability* cap, bool adding)
65 const bool hascap = ((usercaps & cap->GetMask()) != 0);
69 return cap->OnRequest(user, adding);
72 Capability::Bit AllocateBit() const
74 Capability::Bit used = 0;
75 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
77 Capability* cap = i->second;
78 used |= cap->GetMask();
81 for (unsigned int i = 0; i < MAX_CAPS; i++)
83 Capability::Bit bit = (1 << i);
87 throw ModuleException("Too many caps");
90 void OnReloadModuleSave(Module* mod, ReloadModule::CustomData& cd) CXX11_OVERRIDE
92 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnReloadModuleSave()");
96 CapModData* capmoddata = new CapModData;
97 cd.add(this, capmoddata);
99 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
101 Capability* cap = i->second;
102 // Only save users of caps that belong to the module being reloaded
103 if (cap->creator != mod)
106 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Module being reloaded implements cap %s, saving cap users", cap->GetName().c_str());
107 capmoddata->caps.push_back(CapModData::Data(cap));
108 CapModData::Data& capdata = capmoddata->caps.back();
110 // Populate list with uuids of users who are using the cap
111 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
112 for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
114 LocalUser* user = *j;
116 capdata.users.push_back(user->uuid);
121 void OnReloadModuleRestore(Module* mod, void* data) CXX11_OVERRIDE
123 CapModData* capmoddata = static_cast<CapModData*>(data);
124 for (std::vector<CapModData::Data>::const_iterator i = capmoddata->caps.begin(); i != capmoddata->caps.end(); ++i)
126 const CapModData::Data& capdata = *i;
127 Capability* cap = ManagerImpl::Find(capdata.name);
130 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s is no longer available after reload", capdata.name.c_str());
134 // Set back the cap for all users who were using it before the reload
135 for (std::vector<std::string>::const_iterator j = capdata.users.begin(); j != capdata.users.end(); ++j)
137 const std::string& uuid = *j;
138 User* user = ServerInstance->FindUUID(uuid);
141 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User %s is gone when trying to restore cap %s", uuid.c_str(), capdata.name.c_str());
145 cap->set(user, true);
152 ManagerImpl(Module* mod, Events::ModuleEventProvider& evprovref)
154 , ReloadModule::EventListener(mod)
163 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
165 Capability* cap = i->second;
170 void AddCap(Cap::Capability* cap) CXX11_OVERRIDE
172 // No-op if the cap is already registered.
173 // This allows modules to call SetActive() on a cap without checking if it's active first.
174 if (cap->IsRegistered())
177 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Registering cap %s", cap->GetName().c_str());
178 cap->bit = AllocateBit();
179 cap->extitem = &capext;
180 caps.insert(std::make_pair(cap->GetName(), cap));
181 ServerInstance->Modules.AddReferent("cap/" + cap->GetName(), cap);
183 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
186 void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
188 // No-op if the cap is not registered, see AddCap() above
189 if (!cap->IsRegistered())
192 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
194 // Fire the event first so modules can still see who is using the cap which is being unregistered
195 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, false));
197 // Turn off the cap for all users
198 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
199 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
201 LocalUser* user = *i;
202 cap->set(user, false);
205 ServerInstance->Modules.DelReferent(cap);
207 caps.erase(cap->GetName());
210 Capability* Find(const std::string& capname) const CXX11_OVERRIDE
212 CapMap::const_iterator it = caps.find(capname);
213 if (it != caps.end())
218 void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
220 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
221 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
224 Protocol GetProtocol(LocalUser* user) const
226 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
229 void Set302Protocol(LocalUser* user)
231 capext.set(user, capext.get(user) | CAP_302_BIT);
234 bool HandleReq(LocalUser* user, const std::string& reqlist)
236 Ext usercaps = capext.get(user);
237 irc::spacesepstream ss(reqlist);
238 for (std::string capname; ss.GetToken(capname); )
240 bool remove = (capname[0] == '-');
242 capname.erase(capname.begin());
244 Capability* cap = ManagerImpl::Find(capname);
245 if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
249 usercaps = cap->DelFromMask(usercaps);
251 usercaps = cap->AddToMask(usercaps);
254 capext.set(user, usercaps);
258 void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
260 Ext show_caps = (show_all ? ~0 : capext.get(user));
262 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
264 Capability* cap = i->second;
265 if (!(show_caps & cap->GetMask()))
268 if ((show_all) && (!cap->OnList(user)))
273 out.append(cap->GetName());
277 const std::string* capvalue = cap->GetValue(user);
278 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
281 out.append(*capvalue, 0, MAX_VALUE_LENGTH);
288 void HandleClear(LocalUser* user, std::string& result)
290 HandleList(result, user, false, false, true);
297 std::string SerializeCaps(const Extensible* container, void* item, bool human)
299 // XXX: Cast away the const because IS_LOCAL() doesn't handle it
300 LocalUser* user = IS_LOCAL(const_cast<User*>(static_cast<const User*>(container)));
302 return std::string();
304 // List requested caps
306 managerimpl->HandleList(ret, user, false, false);
308 // Serialize cap protocol version. If building a human-readable string append a new token, otherwise append only a single character indicating the version.
309 Cap::Protocol protocol = managerimpl->GetProtocol(user);
311 ret.append("capversion=3.");
312 else if (!ret.empty())
313 ret.erase(ret.length()-1);
315 if (protocol == Cap::CAP_302)
324 Cap::ExtItem::ExtItem(Module* mod)
325 : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
329 std::string Cap::ExtItem::ToHuman(const Extensible* container, void* item) const
331 return SerializeCaps(container, item, true);
334 std::string Cap::ExtItem::ToInternal(const Extensible* container, void* item) const
336 return SerializeCaps(container, item, false);
339 void Cap::ExtItem::FromInternal(Extensible* container, const std::string& value)
341 LocalUser* user = IS_LOCAL(static_cast<User*>(container));
343 return; // Can't happen
345 // Process the cap protocol version which is a single character at the end of the serialized string
346 const char verchar = *value.rbegin();
348 managerimpl->Set302Protocol(user);
350 // Remove the version indicator from the string passed to HandleReq
351 std::string caplist(value, 0, value.size()-1);
352 managerimpl->HandleReq(user, caplist);
355 class CapMessage : public Cap::MessageBase
358 CapMessage(LocalUser* user, const std::string& subcmd, const std::string& result)
359 : Cap::MessageBase(subcmd)
362 PushParamRef(result);
366 class CommandCap : public SplitCommand
368 Events::ModuleEventProvider evprov;
369 Cap::ManagerImpl manager;
370 ClientProtocol::EventProvider protoevprov;
372 void DisplayResult(LocalUser* user, const std::string& subcmd, std::string& result)
374 if (*result.rbegin() == ' ')
375 result.erase(result.end()-1);
376 DisplayResult2(user, subcmd, result);
379 void DisplayResult2(LocalUser* user, const std::string& subcmd, const std::string& result)
381 CapMessage msg(user, subcmd, result);
382 ClientProtocol::Event ev(protoevprov, msg);
389 CommandCap(Module* mod)
390 : SplitCommand(mod, "CAP", 1)
391 , evprov(mod, "event/cap")
392 , manager(mod, evprov)
393 , protoevprov(mod, name)
394 , holdext("cap_hold", ExtensionItem::EXT_USER, mod)
396 works_before_reg = true;
399 CmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE
401 if (user->registered != REG_ALL)
402 holdext.set(user, 1);
404 const std::string& subcommand = parameters[0];
405 if (irc::equals(subcommand, "REQ"))
407 if (parameters.size() < 2)
410 const std::string replysubcmd = (manager.HandleReq(user, parameters[1]) ? "ACK" : "NAK");
411 DisplayResult2(user, replysubcmd, parameters[1]);
413 else if (irc::equals(subcommand, "END"))
417 else if (irc::equals(subcommand, "LS") || irc::equals(subcommand, "LIST"))
419 Cap::Protocol capversion = Cap::CAP_LEGACY;
420 const bool is_ls = (subcommand.length() == 2);
421 if ((is_ls) && (parameters.size() > 1))
423 unsigned int version = ConvToNum<unsigned int>(parameters[1]);
426 capversion = Cap::CAP_302;
427 manager.Set302Protocol(user);
432 // Show values only if supports v3.2 and doing LS
433 manager.HandleList(result, user, is_ls, ((is_ls) && (capversion != Cap::CAP_LEGACY)));
434 DisplayResult(user, subcommand, result);
436 else if (irc::equals(subcommand, "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
439 manager.HandleClear(user, result);
440 DisplayResult(user, "ACK", result);
444 user->WriteNumeric(ERR_INVALIDCAPCMD, subcommand.empty() ? "*" : subcommand, "Invalid CAP subcommand");
452 class ModuleCap : public Module
462 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
464 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
467 Version GetVersion() CXX11_OVERRIDE
469 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
473 MODULE_INIT(ModuleCap)