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"
29 static Cap::ManagerImpl* managerimpl;
31 class Cap::ManagerImpl : public Cap::Manager, public ReloadModule::EventListener
33 /** Stores the cap state of a module being reloaded
40 std::vector<std::string> users;
43 : name(cap->GetName())
47 std::vector<Data> caps;
50 typedef insp::flat_map<std::string, Capability*, irc::insensitive_swo> CapMap;
54 Events::ModuleEventProvider& evprov;
56 static bool CanRequest(LocalUser* user, Ext usercaps, Capability* cap, bool adding)
58 if ((usercaps & cap->GetMask()) == adding)
61 return cap->OnRequest(user, adding);
64 Capability::Bit AllocateBit() const
66 Capability::Bit used = 0;
67 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
69 Capability* cap = i->second;
70 used |= cap->GetMask();
73 for (unsigned int i = 0; i < MAX_CAPS; i++)
75 Capability::Bit bit = (1 << i);
79 throw ModuleException("Too many caps");
82 void OnReloadModuleSave(Module* mod, ReloadModule::CustomData& cd) CXX11_OVERRIDE
84 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnReloadModuleSave()");
88 CapModData* capmoddata = new CapModData;
89 cd.add(this, capmoddata);
91 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
93 Capability* cap = i->second;
94 // Only save users of caps that belong to the module being reloaded
95 if (cap->creator != mod)
98 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Module being reloaded implements cap %s, saving cap users", cap->GetName().c_str());
99 capmoddata->caps.push_back(CapModData::Data(cap));
100 CapModData::Data& capdata = capmoddata->caps.back();
102 // Populate list with uuids of users who are using the cap
103 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
104 for (UserManager::LocalList::const_iterator j = list.begin(); j != list.end(); ++j)
106 LocalUser* user = *j;
108 capdata.users.push_back(user->uuid);
113 void OnReloadModuleRestore(Module* mod, void* data) CXX11_OVERRIDE
115 CapModData* capmoddata = static_cast<CapModData*>(data);
116 for (std::vector<CapModData::Data>::const_iterator i = capmoddata->caps.begin(); i != capmoddata->caps.end(); ++i)
118 const CapModData::Data& capdata = *i;
119 Capability* cap = ManagerImpl::Find(capdata.name);
122 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s is no longer available after reload", capdata.name.c_str());
126 // Set back the cap for all users who were using it before the reload
127 for (std::vector<std::string>::const_iterator j = capdata.users.begin(); j != capdata.users.end(); ++j)
129 const std::string& uuid = *j;
130 User* user = ServerInstance->FindUUID(uuid);
133 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User %s is gone when trying to restore cap %s", uuid.c_str(), capdata.name.c_str());
137 cap->set(user, true);
144 ManagerImpl(Module* mod, Events::ModuleEventProvider& evprovref)
146 , ReloadModule::EventListener(mod)
155 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
157 Capability* cap = i->second;
162 void AddCap(Cap::Capability* cap) CXX11_OVERRIDE
164 // No-op if the cap is already registered.
165 // This allows modules to call SetActive() on a cap without checking if it's active first.
166 if (cap->IsRegistered())
169 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Registering cap %s", cap->GetName().c_str());
170 cap->bit = AllocateBit();
171 cap->extitem = &capext;
172 caps.insert(std::make_pair(cap->GetName(), cap));
174 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
177 void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
179 // No-op if the cap is not registered, see AddCap() above
180 if (!cap->IsRegistered())
183 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
185 // Fire the event first so modules can still see who is using the cap which is being unregistered
186 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, false));
188 // Turn off the cap for all users
189 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
190 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
192 LocalUser* user = *i;
193 cap->set(user, false);
197 caps.erase(cap->GetName());
200 Capability* Find(const std::string& capname) const CXX11_OVERRIDE
202 CapMap::const_iterator it = caps.find(capname);
203 if (it != caps.end())
208 void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
210 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
211 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
214 Protocol GetProtocol(LocalUser* user) const
216 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
219 void Set302Protocol(LocalUser* user)
221 capext.set(user, capext.get(user) | CAP_302_BIT);
224 bool HandleReq(LocalUser* user, const std::string& reqlist)
226 Ext usercaps = capext.get(user);
227 irc::spacesepstream ss(reqlist);
228 for (std::string capname; ss.GetToken(capname); )
230 bool remove = (capname[0] == '-');
232 capname.erase(capname.begin());
234 Capability* cap = ManagerImpl::Find(capname);
235 if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
239 usercaps = cap->DelFromMask(usercaps);
241 usercaps = cap->AddToMask(usercaps);
244 capext.set(user, usercaps);
248 void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
250 Ext show_caps = (show_all ? ~0 : capext.get(user));
252 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
254 Capability* cap = i->second;
255 if (!(show_caps & cap->GetMask()))
258 if ((show_all) && (!cap->OnList(user)))
263 out.append(cap->GetName());
267 const std::string* capvalue = cap->GetValue(user);
268 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
271 out.append(*capvalue, 0, MAX_VALUE_LENGTH);
278 void HandleClear(LocalUser* user, std::string& result)
280 HandleList(result, user, false, false, true);
285 Cap::ExtItem::ExtItem(Module* mod)
286 : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
290 std::string Cap::ExtItem::serialize(SerializeFormat format, const Extensible* container, void* item) const
293 // XXX: Cast away the const because IS_LOCAL() doesn't handle it
294 LocalUser* user = IS_LOCAL(const_cast<User*>(static_cast<const User*>(container)));
295 if ((format == FORMAT_NETWORK) || (!user))
298 // List requested caps
299 managerimpl->HandleList(ret, user, false, false);
301 // Serialize cap protocol version. If building a human-readable string append a new token, otherwise append only a single character indicating the version.
302 Protocol protocol = managerimpl->GetProtocol(user);
303 if (format == FORMAT_USER)
304 ret.append("capversion=3.");
305 else if (!ret.empty())
306 ret.erase(ret.length()-1);
308 if (protocol == CAP_302)
316 void Cap::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
318 if (format == FORMAT_NETWORK)
321 LocalUser* user = IS_LOCAL(static_cast<User*>(container));
323 return; // Can't happen
325 // Process the cap protocol version which is a single character at the end of the serialized string
326 const char verchar = *value.rbegin();
328 managerimpl->Set302Protocol(user);
330 // Remove the version indicator from the string passed to HandleReq
331 std::string caplist(value, 0, value.size()-1);
332 managerimpl->HandleReq(user, caplist);
335 class CommandCap : public SplitCommand
337 Events::ModuleEventProvider evprov;
338 Cap::ManagerImpl manager;
340 static void DisplayResult(LocalUser* user, std::string& result)
342 if (result.size() > 5)
343 result.erase(result.end()-1);
344 user->WriteCommand("CAP", result);
350 CommandCap(Module* mod)
351 : SplitCommand(mod, "CAP", 1)
352 , evprov(mod, "event/cap")
353 , manager(mod, evprov)
354 , holdext("cap_hold", ExtensionItem::EXT_USER, mod)
356 works_before_reg = true;
359 CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) CXX11_OVERRIDE
361 if (user->registered != REG_ALL)
362 holdext.set(user, 1);
364 std::string subcommand(parameters[0].length(), ' ');
365 std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper);
367 if (subcommand == "REQ")
369 if (parameters.size() < 2)
372 std::string result = (manager.HandleReq(user, parameters[1]) ? "ACK :" : "NAK :");
373 result.append(parameters[1]);
374 user->WriteCommand("CAP", result);
376 else if (subcommand == "END")
380 else if ((subcommand == "LS") || (subcommand == "LIST"))
382 const bool is_ls = (subcommand.length() == 2);
383 if ((is_ls) && (parameters.size() > 1) && (parameters[1] == "302"))
384 manager.Set302Protocol(user);
386 std::string result = subcommand + " :";
387 // Show values only if supports v3.2 and doing LS
388 manager.HandleList(result, user, is_ls, ((is_ls) && (manager.GetProtocol(user) != Cap::CAP_LEGACY)));
389 DisplayResult(user, result);
391 else if ((subcommand == "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
393 std::string result = "ACK :";
394 manager.HandleClear(user, result);
395 DisplayResult(user, result);
399 user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, "%s :Invalid CAP subcommand", subcommand.c_str());
407 class ModuleCap : public Module
417 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
419 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
422 Version GetVersion() CXX11_OVERRIDE
424 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
428 MODULE_INIT(ModuleCap)