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));
173 ServerInstance->Modules.AddReferent("cap/" + cap->GetName(), cap);
175 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
178 void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
180 // No-op if the cap is not registered, see AddCap() above
181 if (!cap->IsRegistered())
184 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
186 // Fire the event first so modules can still see who is using the cap which is being unregistered
187 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, false));
189 // Turn off the cap for all users
190 const UserManager::LocalList& list = ServerInstance->Users.GetLocalUsers();
191 for (UserManager::LocalList::const_iterator i = list.begin(); i != list.end(); ++i)
193 LocalUser* user = *i;
194 cap->set(user, false);
197 ServerInstance->Modules.DelReferent(cap);
199 caps.erase(cap->GetName());
202 Capability* Find(const std::string& capname) const CXX11_OVERRIDE
204 CapMap::const_iterator it = caps.find(capname);
205 if (it != caps.end())
210 void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
212 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
213 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
216 Protocol GetProtocol(LocalUser* user) const
218 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
221 void Set302Protocol(LocalUser* user)
223 capext.set(user, capext.get(user) | CAP_302_BIT);
226 bool HandleReq(LocalUser* user, const std::string& reqlist)
228 Ext usercaps = capext.get(user);
229 irc::spacesepstream ss(reqlist);
230 for (std::string capname; ss.GetToken(capname); )
232 bool remove = (capname[0] == '-');
234 capname.erase(capname.begin());
236 Capability* cap = ManagerImpl::Find(capname);
237 if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
241 usercaps = cap->DelFromMask(usercaps);
243 usercaps = cap->AddToMask(usercaps);
246 capext.set(user, usercaps);
250 void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
252 Ext show_caps = (show_all ? ~0 : capext.get(user));
254 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
256 Capability* cap = i->second;
257 if (!(show_caps & cap->GetMask()))
260 if ((show_all) && (!cap->OnList(user)))
265 out.append(cap->GetName());
269 const std::string* capvalue = cap->GetValue(user);
270 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
273 out.append(*capvalue, 0, MAX_VALUE_LENGTH);
280 void HandleClear(LocalUser* user, std::string& result)
282 HandleList(result, user, false, false, true);
287 Cap::ExtItem::ExtItem(Module* mod)
288 : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
292 std::string Cap::ExtItem::serialize(SerializeFormat format, const Extensible* container, void* item) const
295 // XXX: Cast away the const because IS_LOCAL() doesn't handle it
296 LocalUser* user = IS_LOCAL(const_cast<User*>(static_cast<const User*>(container)));
297 if ((format == FORMAT_NETWORK) || (!user))
300 // List requested caps
301 managerimpl->HandleList(ret, user, false, false);
303 // Serialize cap protocol version. If building a human-readable string append a new token, otherwise append only a single character indicating the version.
304 Protocol protocol = managerimpl->GetProtocol(user);
305 if (format == FORMAT_USER)
306 ret.append("capversion=3.");
307 else if (!ret.empty())
308 ret.erase(ret.length()-1);
310 if (protocol == CAP_302)
318 void Cap::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
320 if (format == FORMAT_NETWORK)
323 LocalUser* user = IS_LOCAL(static_cast<User*>(container));
325 return; // Can't happen
327 // Process the cap protocol version which is a single character at the end of the serialized string
328 const char verchar = *value.rbegin();
330 managerimpl->Set302Protocol(user);
332 // Remove the version indicator from the string passed to HandleReq
333 std::string caplist(value, 0, value.size()-1);
334 managerimpl->HandleReq(user, caplist);
337 class CommandCap : public SplitCommand
339 Events::ModuleEventProvider evprov;
340 Cap::ManagerImpl manager;
342 static void DisplayResult(LocalUser* user, std::string& result)
344 if (*result.rbegin() == ' ')
345 result.erase(result.end()-1);
346 user->WriteCommand("CAP", result);
352 CommandCap(Module* mod)
353 : SplitCommand(mod, "CAP", 1)
354 , evprov(mod, "event/cap")
355 , manager(mod, evprov)
356 , holdext("cap_hold", ExtensionItem::EXT_USER, mod)
358 works_before_reg = true;
361 CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) CXX11_OVERRIDE
363 if (user->registered != REG_ALL)
364 holdext.set(user, 1);
366 std::string subcommand(parameters[0].length(), ' ');
367 std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper);
369 if (subcommand == "REQ")
371 if (parameters.size() < 2)
374 std::string result = (manager.HandleReq(user, parameters[1]) ? "ACK :" : "NAK :");
375 result.append(parameters[1]);
376 user->WriteCommand("CAP", result);
378 else if (subcommand == "END")
382 else if ((subcommand == "LS") || (subcommand == "LIST"))
384 const bool is_ls = (subcommand.length() == 2);
385 if ((is_ls) && (parameters.size() > 1) && (parameters[1] == "302"))
386 manager.Set302Protocol(user);
388 std::string result = subcommand + " :";
389 // Show values only if supports v3.2 and doing LS
390 manager.HandleList(result, user, is_ls, ((is_ls) && (manager.GetProtocol(user) != Cap::CAP_LEGACY)));
391 DisplayResult(user, result);
393 else if ((subcommand == "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
395 std::string result = "ACK :";
396 manager.HandleClear(user, result);
397 DisplayResult(user, result);
401 user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, subcommand, "Invalid CAP subcommand");
409 class ModuleCap : public Module
419 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
421 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
424 Version GetVersion() CXX11_OVERRIDE
426 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
430 MODULE_INIT(ModuleCap)