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