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