]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cap.cpp
m_cap Save and restore the cap state of a module when it is reloaded
[user/henk/code/inspircd.git] / src / modules / m_cap.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2015 Attila Molnar <attilamolnar@hush.com>
5  *
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.
9  *
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
13  * details.
14  *
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/>.
17  */
18
19
20 #include "inspircd.h"
21 #include "modules/reload.h"
22 #include "modules/cap.h"
23
24 namespace Cap
25 {
26         class ManagerImpl;
27 }
28
29 static Cap::ManagerImpl* managerimpl;
30
31 class Cap::ManagerImpl : public Cap::Manager, public ReloadModule::EventListener
32 {
33         /** Stores the cap state of a module being reloaded
34          */
35         struct CapModData
36         {
37                 struct Data
38                 {
39                         std::string name;
40                         std::vector<std::string> users;
41
42                         Data(Capability* cap)
43                                 : name(cap->GetName())
44                         {
45                         }
46                 };
47                 std::vector<Data> caps;
48         };
49
50         typedef insp::flat_map<std::string, Capability*, irc::insensitive_swo> CapMap;
51
52         ExtItem capext;
53         CapMap caps;
54         Events::ModuleEventProvider& evprov;
55
56         static bool CanRequest(LocalUser* user, Ext usercaps, Capability* cap, bool adding)
57         {
58                 if ((usercaps & cap->GetMask()) == adding)
59                         return true;
60
61                 return cap->OnRequest(user, adding);
62         }
63
64         Capability::Bit AllocateBit() const
65         {
66                 Capability::Bit used = 0;
67                 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
68                 {
69                         Capability* cap = i->second;
70                         used |= cap->GetMask();
71                 }
72
73                 for (unsigned int i = 0; i < MAX_CAPS; i++)
74                 {
75                         Capability::Bit bit = (1 << i);
76                         if (!(used & bit))
77                                 return bit;
78                 }
79                 throw ModuleException("Too many caps");
80         }
81
82         void OnReloadModuleSave(Module* mod, ReloadModule::CustomData& cd) CXX11_OVERRIDE
83         {
84                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "OnReloadModuleSave()");
85                 if (mod == creator)
86                         return;
87
88                 CapModData* capmoddata = new CapModData;
89                 cd.add(this, capmoddata);
90
91                 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
92                 {
93                         Capability* cap = i->second;
94                         // Only save users of caps that belong to the module being reloaded
95                         if (cap->creator != mod)
96                                 continue;
97
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();
101
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)
105                         {
106                                 LocalUser* user = *j;
107                                 if (cap->get(user))
108                                         capdata.users.push_back(user->uuid);
109                         }
110                 }
111         }
112
113         void OnReloadModuleRestore(Module* mod, void* data) CXX11_OVERRIDE
114         {
115                 CapModData* capmoddata = static_cast<CapModData*>(data);
116                 for (std::vector<CapModData::Data>::const_iterator i = capmoddata->caps.begin(); i != capmoddata->caps.end(); ++i)
117                 {
118                         const CapModData::Data& capdata = *i;
119                         Capability* cap = ManagerImpl::Find(capdata.name);
120                         if (!cap)
121                         {
122                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s is no longer available after reload", capdata.name.c_str());
123                                 continue;
124                         }
125
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)
128                         {
129                                 const std::string& uuid = *j;
130                                 User* user = ServerInstance->FindUUID(uuid);
131                                 if (!user)
132                                 {
133                                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "User %s is gone when trying to restore cap %s", uuid.c_str(), capdata.name.c_str());
134                                         continue;
135                                 }
136
137                                 cap->set(user, true);
138                         }
139                 }
140                 delete capmoddata;
141         }
142
143  public:
144         ManagerImpl(Module* mod, Events::ModuleEventProvider& evprovref)
145                 : Cap::Manager(mod)
146                 , ReloadModule::EventListener(mod)
147                 , capext(mod)
148                 , evprov(evprovref)
149         {
150                 managerimpl = this;
151         }
152
153         ~ManagerImpl()
154         {
155                 for (CapMap::iterator i = caps.begin(); i != caps.end(); ++i)
156                 {
157                         Capability* cap = i->second;
158                         cap->Unregister();
159                 }
160         }
161
162         void AddCap(Cap::Capability* cap) CXX11_OVERRIDE
163         {
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())
167                         return;
168
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
174                 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
175         }
176
177         void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
178         {
179                 // No-op if the cap is not registered, see AddCap() above
180                 if (!cap->IsRegistered())
181                         return;
182
183                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
184
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));
187
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)
191                 {
192                         LocalUser* user = *i;
193                         cap->set(user, false);
194                 }
195
196                 cap->Unregister();
197                 caps.erase(cap->GetName());
198         }
199
200         Capability* Find(const std::string& capname) const CXX11_OVERRIDE
201         {
202                 CapMap::const_iterator it = caps.find(capname);
203                 if (it != caps.end())
204                         return it->second;
205                 return NULL;
206         }
207
208         void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
209         {
210                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
211                 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
212         }
213
214         Protocol GetProtocol(LocalUser* user) const
215         {
216                 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
217         }
218
219         void Set302Protocol(LocalUser* user)
220         {
221                 capext.set(user, capext.get(user) | CAP_302_BIT);
222         }
223
224         bool HandleReq(LocalUser* user, const std::string& reqlist)
225         {
226                 Ext usercaps = capext.get(user);
227                 irc::spacesepstream ss(reqlist);
228                 for (std::string capname; ss.GetToken(capname); )
229                 {
230                         bool remove = (capname[0] == '-');
231                         if (remove)
232                                 capname.erase(capname.begin());
233
234                         Capability* cap = ManagerImpl::Find(capname);
235                         if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
236                                 return false;
237
238                         if (remove)
239                                 usercaps = cap->DelFromMask(usercaps);
240                         else
241                                 usercaps = cap->AddToMask(usercaps);
242                 }
243
244                 capext.set(user, usercaps);
245                 return true;
246         }
247
248         void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
249         {
250                 Ext show_caps = (show_all ? ~0 : capext.get(user));
251
252                 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
253                 {
254                         Capability* cap = i->second;
255                         if (!(show_caps & cap->GetMask()))
256                                 continue;
257
258                         if ((show_all) && (!cap->OnList(user)))
259                                 continue;
260
261                         if (minus_prefix)
262                                 out.push_back('-');
263                         out.append(cap->GetName());
264
265                         if (show_values)
266                         {
267                                 const std::string* capvalue = cap->GetValue(user);
268                                 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
269                                 {
270                                         out.push_back('=');
271                                         out.append(*capvalue, 0, MAX_VALUE_LENGTH);
272                                 }
273                         }
274                         out.push_back(' ');
275                 }
276         }
277
278         void HandleClear(LocalUser* user, std::string& result)
279         {
280                 HandleList(result, user, false, false, true);
281                 capext.unset(user);
282         }
283 };
284
285 Cap::ExtItem::ExtItem(Module* mod)
286         : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
287 {
288 }
289
290 std::string Cap::ExtItem::serialize(SerializeFormat format, const Extensible* container, void* item) const
291 {
292         std::string ret;
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))
296                 return ret;
297
298         // List requested caps
299         managerimpl->HandleList(ret, user, false, false);
300
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);
307
308         if (protocol == CAP_302)
309                 ret.push_back('2');
310         else
311                 ret.push_back('1');
312
313         return ret;
314 }
315
316 void Cap::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
317 {
318         if (format == FORMAT_NETWORK)
319                 return;
320
321         LocalUser* user = IS_LOCAL(static_cast<User*>(container));
322         if (!user)
323                 return; // Can't happen
324
325         // Process the cap protocol version which is a single character at the end of the serialized string
326         const char verchar = *value.rbegin();
327         if (verchar == '2')
328                 managerimpl->Set302Protocol(user);
329
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);
333 }
334
335 class CommandCap : public SplitCommand
336 {
337         Events::ModuleEventProvider evprov;
338         Cap::ManagerImpl manager;
339
340         static void DisplayResult(LocalUser* user, std::string& result)
341         {
342                 if (result.size() > 5)
343                         result.erase(result.end()-1);
344                 user->WriteCommand("CAP", result);
345         }
346
347  public:
348         LocalIntExt holdext;
349
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)
355         {
356                 works_before_reg = true;
357         }
358
359         CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) CXX11_OVERRIDE
360         {
361                 if (user->registered != REG_ALL)
362                         holdext.set(user, 1);
363
364                 std::string subcommand(parameters[0].length(), ' ');
365                 std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper);
366
367                 if (subcommand == "REQ")
368                 {
369                         if (parameters.size() < 2)
370                                 return CMD_FAILURE;
371
372                         std::string result = (manager.HandleReq(user, parameters[1]) ? "ACK :" : "NAK :");
373                         result.append(parameters[1]);
374                         user->WriteCommand("CAP", result);
375                 }
376                 else if (subcommand == "END")
377                 {
378                         holdext.unset(user);
379                 }
380                 else if ((subcommand == "LS") || (subcommand == "LIST"))
381                 {
382                         const bool is_ls = (subcommand.length() == 2);
383                         if ((is_ls) && (parameters.size() > 1) && (parameters[1] == "302"))
384                                 manager.Set302Protocol(user);
385
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);
390                 }
391                 else if ((subcommand == "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
392                 {
393                         std::string result = "ACK :";
394                         manager.HandleClear(user, result);
395                         DisplayResult(user, result);
396                 }
397                 else
398                 {
399                         user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, "%s :Invalid CAP subcommand", subcommand.c_str());
400                         return CMD_FAILURE;
401                 }
402
403                 return CMD_SUCCESS;
404         }
405 };
406
407 class ModuleCap : public Module
408 {
409         CommandCap cmd;
410
411  public:
412         ModuleCap()
413                 : cmd(this)
414         {
415         }
416
417         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
418         {
419                 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
420         }
421
422         Version GetVersion() CXX11_OVERRIDE
423         {
424                 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
425         }
426 };
427
428 MODULE_INIT(ModuleCap)