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