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