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