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