]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_callerid.cpp
Update copyright headers.
[user/henk/code/inspircd.git] / src / modules / m_callerid.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2013, 2017-2019 Sadie Powell <sadie@witchery.services>
5  *   Copyright (C) 2013 Adam <Adam@anope.org>
6  *   Copyright (C) 2012-2016 Attila Molnar <attilamolnar@hush.com>
7  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
8  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
9  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10  *   Copyright (C) 2009 John Brooks <special@inspircd.org>
11  *   Copyright (C) 2008-2009 Robin Burchell <robin+git@viroteck.net>
12  *   Copyright (C) 2008, 2010 Craig Edwards <brain@inspircd.org>
13  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
14  *
15  * This file is part of InspIRCd.  InspIRCd is free software: you can
16  * redistribute it and/or modify it under the terms of the GNU General Public
17  * License as published by the Free Software Foundation, version 2.
18  *
19  * This program is distributed in the hope that it will be useful, but WITHOUT
20  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
21  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
22  * details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
26  */
27
28
29 #include "inspircd.h"
30 #include "modules/callerid.h"
31 #include "modules/ctctags.h"
32
33 enum
34 {
35         RPL_ACCEPTLIST = 281,
36         RPL_ENDOFACCEPT = 282,
37         ERR_ACCEPTFULL = 456,
38         ERR_ACCEPTEXIST = 457,
39         ERR_ACCEPTNOT = 458,
40         ERR_TARGUMODEG = 716,
41         RPL_TARGNOTIFY = 717,
42         RPL_UMODEGMSG = 718
43 };
44
45 class callerid_data
46 {
47  public:
48         typedef insp::flat_set<User*> UserSet;
49         typedef std::vector<callerid_data*> CallerIdDataSet;
50
51         time_t lastnotify;
52
53         /** Users I accept messages from
54          */
55         UserSet accepting;
56
57         /** Users who list me as accepted
58          */
59         CallerIdDataSet wholistsme;
60
61         callerid_data() : lastnotify(0) { }
62
63         std::string ToString(bool human) const
64         {
65                 std::ostringstream oss;
66                 oss << lastnotify;
67                 for (UserSet::const_iterator i = accepting.begin(); i != accepting.end(); ++i)
68                 {
69                         User* u = *i;
70                         // Encode UIDs.
71                         oss << "," << (human ? u->nick : u->uuid);
72                 }
73                 return oss.str();
74         }
75 };
76
77 struct CallerIDExtInfo : public ExtensionItem
78 {
79         CallerIDExtInfo(Module* parent)
80                 : ExtensionItem("callerid_data", ExtensionItem::EXT_USER, parent)
81         {
82         }
83
84         std::string ToHuman(const Extensible* container, void* item) const CXX11_OVERRIDE
85         {
86                 callerid_data* dat = static_cast<callerid_data*>(item);
87                 return dat->ToString(true);
88         }
89
90         std::string ToInternal(const Extensible* container, void* item) const CXX11_OVERRIDE
91         {
92                 callerid_data* dat = static_cast<callerid_data*>(item);
93                 return dat->ToString(false);
94         }
95
96         void FromInternal(Extensible* container, const std::string& value) CXX11_OVERRIDE
97         {
98                 void* old = get_raw(container);
99                 if (old)
100                         this->free(NULL, old);
101                 callerid_data* dat = new callerid_data;
102                 set_raw(container, dat);
103
104                 irc::commasepstream s(value);
105                 std::string tok;
106                 if (s.GetToken(tok))
107                         dat->lastnotify = ConvToNum<time_t>(tok);
108
109                 while (s.GetToken(tok))
110                 {
111                         User *u = ServerInstance->FindNick(tok);
112                         if ((u) && (u->registered == REG_ALL) && (!u->quitting))
113                         {
114                                 if (dat->accepting.insert(u).second)
115                                 {
116                                         callerid_data* other = this->get(u, true);
117                                         other->wholistsme.push_back(dat);
118                                 }
119                         }
120                 }
121         }
122
123         callerid_data* get(User* user, bool create)
124         {
125                 callerid_data* dat = static_cast<callerid_data*>(get_raw(user));
126                 if (create && !dat)
127                 {
128                         dat = new callerid_data;
129                         set_raw(user, dat);
130                 }
131                 return dat;
132         }
133
134         void free(Extensible* container, void* item) CXX11_OVERRIDE
135         {
136                 callerid_data* dat = static_cast<callerid_data*>(item);
137
138                 // We need to walk the list of users on our accept list, and remove ourselves from their wholistsme.
139                 for (callerid_data::UserSet::iterator it = dat->accepting.begin(); it != dat->accepting.end(); ++it)
140                 {
141                         callerid_data *targ = this->get(*it, false);
142
143                         if (!targ)
144                         {
145                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (1)");
146                                 continue; // shouldn't happen, but oh well.
147                         }
148
149                         if (!stdalgo::vector::swaperase(targ->wholistsme, dat))
150                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (2)");
151                 }
152                 delete dat;
153         }
154 };
155
156 class CommandAccept : public Command
157 {
158         /** Pair: first is the target, second is true to add, false to remove
159          */
160         typedef std::pair<User*, bool> ACCEPTAction;
161
162         static ACCEPTAction GetTargetAndAction(std::string& tok, User* cmdfrom = NULL)
163         {
164                 bool remove = (tok[0] == '-');
165                 if ((remove) || (tok[0] == '+'))
166                         tok.erase(tok.begin());
167
168                 User* target;
169                 if (!cmdfrom || !IS_LOCAL(cmdfrom))
170                         target = ServerInstance->FindNick(tok);
171                 else
172                         target = ServerInstance->FindNickOnly(tok);
173
174                 if ((!target) || (target->registered != REG_ALL) || (target->quitting))
175                         target = NULL;
176
177                 return std::make_pair(target, !remove);
178         }
179
180 public:
181         CallerIDExtInfo extInfo;
182         unsigned int maxaccepts;
183         CommandAccept(Module* Creator) : Command(Creator, "ACCEPT", 1),
184                 extInfo(Creator)
185         {
186                 allow_empty_last_param = false;
187                 syntax = "*|(+|-)<nick>[,(+|-)<nick>]+";
188                 TRANSLATE1(TR_CUSTOM);
189         }
190
191         void EncodeParameter(std::string& parameter, unsigned int index) CXX11_OVERRIDE
192         {
193                 // Send lists as-is (part of 2.0 compat)
194                 if (parameter.find(',') != std::string::npos)
195                         return;
196
197                 // Convert a (+|-)<nick> into a [-]<uuid>
198                 ACCEPTAction action = GetTargetAndAction(parameter);
199                 if (!action.first)
200                         return;
201
202                 parameter = (action.second ? "" : "-") + action.first->uuid;
203         }
204
205         /** Will take any number of nicks (up to MaxTargets), which can be seperated by commas.
206          * - in front of any nick removes, and an * lists. This effectively means you can do:
207          * /accept nick1,nick2,nick3,*
208          * to add 3 nicks and then show your list
209          */
210         CmdResult Handle(User* user, const Params& parameters) CXX11_OVERRIDE
211         {
212                 if (CommandParser::LoopCall(user, this, parameters, 0))
213                         return CMD_SUCCESS;
214
215                 /* Even if callerid mode is not set, we let them manage their ACCEPT list so that if they go +g they can
216                  * have a list already setup. */
217
218                 if (parameters[0] == "*")
219                 {
220                         ListAccept(user);
221                         return CMD_SUCCESS;
222                 }
223
224                 std::string tok = parameters[0];
225                 ACCEPTAction action = GetTargetAndAction(tok, user);
226                 if (!action.first)
227                 {
228                         user->WriteNumeric(Numerics::NoSuchNick(tok));
229                         return CMD_FAILURE;
230                 }
231
232                 if ((!IS_LOCAL(user)) && (!IS_LOCAL(action.first)))
233                         // Neither source nor target is local, forward the command to the server of target
234                         return CMD_SUCCESS;
235
236                 // The second item in the pair is true if the first char is a '+' (or nothing), false if it's a '-'
237                 if (action.second)
238                         return (AddAccept(user, action.first) ? CMD_SUCCESS : CMD_FAILURE);
239                 else
240                         return (RemoveAccept(user, action.first) ? CMD_SUCCESS : CMD_FAILURE);
241         }
242
243         RouteDescriptor GetRouting(User* user, const Params& parameters) CXX11_OVERRIDE
244         {
245                 // There is a list in parameters[0] in two cases:
246                 // Either when the source is remote, this happens because 2.0 servers send comma seperated uuid lists,
247                 // we don't split those but broadcast them, as before.
248                 //
249                 // Or if the source is local then LoopCall() runs OnPostCommand() after each entry in the list,
250                 // meaning the linking module has sent an ACCEPT already for each entry in the list to the
251                 // appropiate server and the ACCEPT with the list of nicks (this) doesn't need to be sent anywhere.
252                 if ((!IS_LOCAL(user)) && (parameters[0].find(',') != std::string::npos))
253                         return ROUTE_BROADCAST;
254
255                 // Find the target
256                 std::string targetstring = parameters[0];
257                 ACCEPTAction action = GetTargetAndAction(targetstring, user);
258                 if (!action.first)
259                         // Target is a "*" or source is local and the target is a list of nicks
260                         return ROUTE_LOCALONLY;
261
262                 // Route to the server of the target
263                 return ROUTE_UNICAST(action.first->server);
264         }
265
266         void ListAccept(User* user)
267         {
268                 callerid_data* dat = extInfo.get(user, false);
269                 if (dat)
270                 {
271                         for (callerid_data::UserSet::iterator i = dat->accepting.begin(); i != dat->accepting.end(); ++i)
272                                 user->WriteNumeric(RPL_ACCEPTLIST, (*i)->nick);
273                 }
274                 user->WriteNumeric(RPL_ENDOFACCEPT, "End of ACCEPT list");
275         }
276
277         bool AddAccept(User* user, User* whotoadd)
278         {
279                 // Add this user to my accept list first, so look me up..
280                 callerid_data* dat = extInfo.get(user, true);
281                 if (dat->accepting.size() >= maxaccepts)
282                 {
283                         user->WriteNumeric(ERR_ACCEPTFULL, InspIRCd::Format("Accept list is full (limit is %d)", maxaccepts));
284                         return false;
285                 }
286                 if (!dat->accepting.insert(whotoadd).second)
287                 {
288                         user->WriteNumeric(ERR_ACCEPTEXIST, whotoadd->nick, "is already on your accept list");
289                         return false;
290                 }
291
292                 // Now, look them up, and add me to their list
293                 callerid_data *targ = extInfo.get(whotoadd, true);
294                 targ->wholistsme.push_back(dat);
295
296                 user->WriteNotice(whotoadd->nick + " is now on your accept list");
297                 return true;
298         }
299
300         bool RemoveAccept(User* user, User* whotoremove)
301         {
302                 // Remove them from my list, so look up my list..
303                 callerid_data* dat = extInfo.get(user, false);
304                 if (!dat)
305                 {
306                         user->WriteNumeric(ERR_ACCEPTNOT, whotoremove->nick, "is not on your accept list");
307                         return false;
308                 }
309                 if (!dat->accepting.erase(whotoremove))
310                 {
311                         user->WriteNumeric(ERR_ACCEPTNOT, whotoremove->nick, "is not on your accept list");
312                         return false;
313                 }
314
315                 // Look up their list to remove me.
316                 callerid_data *dat2 = extInfo.get(whotoremove, false);
317                 if (!dat2)
318                 {
319                         // How the fuck is this possible.
320                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (3)");
321                         return false;
322                 }
323
324                 if (!stdalgo::vector::swaperase(dat2->wholistsme, dat))
325                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (4)");
326
327
328                 user->WriteNotice(whotoremove->nick + " is no longer on your accept list");
329                 return true;
330         }
331 };
332
333 class CallerIDAPIImpl : public CallerID::APIBase
334 {
335  private:
336         CallerIDExtInfo& ext;
337
338  public:
339         CallerIDAPIImpl(Module* Creator, CallerIDExtInfo& Ext)
340                 : CallerID::APIBase(Creator)
341                 , ext(Ext)
342         {
343         }
344
345         bool IsOnAcceptList(User* source, User* target) CXX11_OVERRIDE
346         {
347                 callerid_data* dat = ext.get(target, true);
348                 return dat->accepting.count(source);
349         }
350 };
351
352
353 class ModuleCallerID
354         : public Module
355         , public CTCTags::EventListener
356 {
357         CommandAccept cmd;
358         CallerIDAPIImpl api;
359         SimpleUserModeHandler myumode;
360
361         // Configuration variables:
362         bool tracknick; // Allow ACCEPT entries to update with nick changes.
363         unsigned int notify_cooldown; // Seconds between notifications.
364
365         /** Removes a user from all accept lists
366          * @param who The user to remove from accepts
367          */
368         void RemoveFromAllAccepts(User* who)
369         {
370                 // First, find the list of people who have me on accept
371                 callerid_data *userdata = cmd.extInfo.get(who, false);
372                 if (!userdata)
373                         return;
374
375                 // Iterate over the list of people who accept me, and remove all entries
376                 for (callerid_data::CallerIdDataSet::iterator it = userdata->wholistsme.begin(); it != userdata->wholistsme.end(); ++it)
377                 {
378                         callerid_data *dat = *(it);
379
380                         // Find me on their callerid list
381                         if (!dat->accepting.erase(who))
382                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (5)");
383                 }
384
385                 userdata->wholistsme.clear();
386         }
387
388 public:
389         ModuleCallerID()
390                 : CTCTags::EventListener(this)
391                 , cmd(this)
392                 , api(this, cmd.extInfo)
393                 , myumode(this, "callerid", 'g')
394         {
395         }
396
397         Version GetVersion() CXX11_OVERRIDE
398         {
399                 return Version("Implementation of callerid, provides user mode +g and the ACCEPT command", VF_COMMON | VF_VENDOR);
400         }
401
402         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
403         {
404                 tokens["ACCEPT"] = ConvToStr(cmd.maxaccepts);
405                 tokens["CALLERID"] = ConvToStr(myumode.GetModeChar());
406         }
407
408         ModResult HandleMessage(User* user, const MessageTarget& target)
409         {
410                 if (!IS_LOCAL(user) || target.type != MessageTarget::TYPE_USER)
411                         return MOD_RES_PASSTHRU;
412
413                 User* dest = target.Get<User>();
414                 if (!dest->IsModeSet(myumode) || (user == dest))
415                         return MOD_RES_PASSTHRU;
416
417                 if (user->HasPrivPermission("users/ignore-callerid"))
418                         return MOD_RES_PASSTHRU;
419
420                 callerid_data* dat = cmd.extInfo.get(dest, true);
421                 if (!dat->accepting.count(user))
422                 {
423                         time_t now = ServerInstance->Time();
424                         /* +g and *not* accepted */
425                         user->WriteNumeric(ERR_TARGUMODEG, dest->nick, "is in +g mode (server-side ignore).");
426                         if (now > (dat->lastnotify + (time_t)notify_cooldown))
427                         {
428                                 user->WriteNumeric(RPL_TARGNOTIFY, dest->nick, "has been informed that you messaged them.");
429                                 dest->WriteRemoteNumeric(RPL_UMODEGMSG, user->nick, InspIRCd::Format("%s@%s", user->ident.c_str(), user->GetDisplayedHost().c_str()), InspIRCd::Format("is messaging you, and you have user mode +g set. Use /ACCEPT +%s to allow.",
430                                                 user->nick.c_str()));
431                                 dat->lastnotify = now;
432                         }
433                         return MOD_RES_DENY;
434                 }
435                 return MOD_RES_PASSTHRU;
436         }
437
438         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
439         {
440                 return HandleMessage(user, target);
441         }
442
443         ModResult OnUserPreTagMessage(User* user, const MessageTarget& target, CTCTags::TagMessageDetails& details) CXX11_OVERRIDE
444         {
445                 return HandleMessage(user, target);
446         }
447
448         void OnUserPostNick(User* user, const std::string& oldnick) CXX11_OVERRIDE
449         {
450                 if (!tracknick)
451                         RemoveFromAllAccepts(user);
452         }
453
454         void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE
455         {
456                 RemoveFromAllAccepts(user);
457         }
458
459         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
460         {
461                 ConfigTag* tag = ServerInstance->Config->ConfValue("callerid");
462                 cmd.maxaccepts = tag->getUInt("maxaccepts", 30);
463                 tracknick = tag->getBool("tracknick");
464                 notify_cooldown = tag->getDuration("cooldown", 60);
465         }
466
467         void Prioritize() CXX11_OVERRIDE
468         {
469                 // Want to be after modules like silence or services_account
470                 ServerInstance->Modules->SetPriority(this, I_OnUserPreMessage, PRIORITY_LAST);
471         }
472 };
473
474 MODULE_INIT(ModuleCallerID)