]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_cap.cpp
Convert WriteNumeric() calls to pass the parameters of the numeric as method parameters
[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                 ServerInstance->Modules.AddReferent("cap/" + cap->GetName(), cap);
174
175                 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapAddDel, (cap, true));
176         }
177
178         void DelCap(Cap::Capability* cap) CXX11_OVERRIDE
179         {
180                 // No-op if the cap is not registered, see AddCap() above
181                 if (!cap->IsRegistered())
182                         return;
183
184                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Unregistering cap %s", cap->GetName().c_str());
185
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));
188
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)
192                 {
193                         LocalUser* user = *i;
194                         cap->set(user, false);
195                 }
196
197                 ServerInstance->Modules.DelReferent(cap);
198                 cap->Unregister();
199                 caps.erase(cap->GetName());
200         }
201
202         Capability* Find(const std::string& capname) const CXX11_OVERRIDE
203         {
204                 CapMap::const_iterator it = caps.find(capname);
205                 if (it != caps.end())
206                         return it->second;
207                 return NULL;
208         }
209
210         void NotifyValueChange(Capability* cap) CXX11_OVERRIDE
211         {
212                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Cap %s changed value", cap->GetName().c_str());
213                 FOREACH_MOD_CUSTOM(evprov, Cap::EventListener, OnCapValueChange, (cap));
214         }
215
216         Protocol GetProtocol(LocalUser* user) const
217         {
218                 return ((capext.get(user) & CAP_302_BIT) ? CAP_302 : CAP_LEGACY);
219         }
220
221         void Set302Protocol(LocalUser* user)
222         {
223                 capext.set(user, capext.get(user) | CAP_302_BIT);
224         }
225
226         bool HandleReq(LocalUser* user, const std::string& reqlist)
227         {
228                 Ext usercaps = capext.get(user);
229                 irc::spacesepstream ss(reqlist);
230                 for (std::string capname; ss.GetToken(capname); )
231                 {
232                         bool remove = (capname[0] == '-');
233                         if (remove)
234                                 capname.erase(capname.begin());
235
236                         Capability* cap = ManagerImpl::Find(capname);
237                         if ((!cap) || (!CanRequest(user, usercaps, cap, !remove)))
238                                 return false;
239
240                         if (remove)
241                                 usercaps = cap->DelFromMask(usercaps);
242                         else
243                                 usercaps = cap->AddToMask(usercaps);
244                 }
245
246                 capext.set(user, usercaps);
247                 return true;
248         }
249
250         void HandleList(std::string& out, LocalUser* user, bool show_all, bool show_values, bool minus_prefix = false) const
251         {
252                 Ext show_caps = (show_all ? ~0 : capext.get(user));
253
254                 for (CapMap::const_iterator i = caps.begin(); i != caps.end(); ++i)
255                 {
256                         Capability* cap = i->second;
257                         if (!(show_caps & cap->GetMask()))
258                                 continue;
259
260                         if ((show_all) && (!cap->OnList(user)))
261                                 continue;
262
263                         if (minus_prefix)
264                                 out.push_back('-');
265                         out.append(cap->GetName());
266
267                         if (show_values)
268                         {
269                                 const std::string* capvalue = cap->GetValue(user);
270                                 if ((capvalue) && (!capvalue->empty()) && (capvalue->find(' ') == std::string::npos))
271                                 {
272                                         out.push_back('=');
273                                         out.append(*capvalue, 0, MAX_VALUE_LENGTH);
274                                 }
275                         }
276                         out.push_back(' ');
277                 }
278         }
279
280         void HandleClear(LocalUser* user, std::string& result)
281         {
282                 HandleList(result, user, false, false, true);
283                 capext.unset(user);
284         }
285 };
286
287 Cap::ExtItem::ExtItem(Module* mod)
288         : LocalIntExt("caps", ExtensionItem::EXT_USER, mod)
289 {
290 }
291
292 std::string Cap::ExtItem::serialize(SerializeFormat format, const Extensible* container, void* item) const
293 {
294         std::string ret;
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))
298                 return ret;
299
300         // List requested caps
301         managerimpl->HandleList(ret, user, false, false);
302
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);
309
310         if (protocol == CAP_302)
311                 ret.push_back('2');
312         else
313                 ret.push_back('1');
314
315         return ret;
316 }
317
318 void Cap::ExtItem::unserialize(SerializeFormat format, Extensible* container, const std::string& value)
319 {
320         if (format == FORMAT_NETWORK)
321                 return;
322
323         LocalUser* user = IS_LOCAL(static_cast<User*>(container));
324         if (!user)
325                 return; // Can't happen
326
327         // Process the cap protocol version which is a single character at the end of the serialized string
328         const char verchar = *value.rbegin();
329         if (verchar == '2')
330                 managerimpl->Set302Protocol(user);
331
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);
335 }
336
337 class CommandCap : public SplitCommand
338 {
339         Events::ModuleEventProvider evprov;
340         Cap::ManagerImpl manager;
341
342         static void DisplayResult(LocalUser* user, std::string& result)
343         {
344                 if (*result.rbegin() == ' ')
345                         result.erase(result.end()-1);
346                 user->WriteCommand("CAP", result);
347         }
348
349  public:
350         LocalIntExt holdext;
351
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)
357         {
358                 works_before_reg = true;
359         }
360
361         CmdResult HandleLocal(const std::vector<std::string>& parameters, LocalUser* user) CXX11_OVERRIDE
362         {
363                 if (user->registered != REG_ALL)
364                         holdext.set(user, 1);
365
366                 std::string subcommand(parameters[0].length(), ' ');
367                 std::transform(parameters[0].begin(), parameters[0].end(), subcommand.begin(), ::toupper);
368
369                 if (subcommand == "REQ")
370                 {
371                         if (parameters.size() < 2)
372                                 return CMD_FAILURE;
373
374                         std::string result = (manager.HandleReq(user, parameters[1]) ? "ACK :" : "NAK :");
375                         result.append(parameters[1]);
376                         user->WriteCommand("CAP", result);
377                 }
378                 else if (subcommand == "END")
379                 {
380                         holdext.unset(user);
381                 }
382                 else if ((subcommand == "LS") || (subcommand == "LIST"))
383                 {
384                         const bool is_ls = (subcommand.length() == 2);
385                         if ((is_ls) && (parameters.size() > 1) && (parameters[1] == "302"))
386                                 manager.Set302Protocol(user);
387
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);
392                 }
393                 else if ((subcommand == "CLEAR") && (manager.GetProtocol(user) == Cap::CAP_LEGACY))
394                 {
395                         std::string result = "ACK :";
396                         manager.HandleClear(user, result);
397                         DisplayResult(user, result);
398                 }
399                 else
400                 {
401                         user->WriteNumeric(ERR_INVALIDCAPSUBCOMMAND, subcommand, "Invalid CAP subcommand");
402                         return CMD_FAILURE;
403                 }
404
405                 return CMD_SUCCESS;
406         }
407 };
408
409 class ModuleCap : public Module
410 {
411         CommandCap cmd;
412
413  public:
414         ModuleCap()
415                 : cmd(this)
416         {
417         }
418
419         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
420         {
421                 return (cmd.holdext.get(user) ? MOD_RES_DENY : MOD_RES_PASSTHRU);
422         }
423
424         Version GetVersion() CXX11_OVERRIDE
425         {
426                 return Version("Provides support for CAP capability negotiation", VF_VENDOR);
427         }
428 };
429
430 MODULE_INIT(ModuleCap)