]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_callerid.cpp
sslinfo: use the SSL certificate API to get user SSL certificates.
[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 #include "modules/callerid.h"
25 #include "modules/ctctags.h"
26
27 enum
28 {
29         RPL_ACCEPTLIST = 281,
30         RPL_ENDOFACCEPT = 282,
31         ERR_ACCEPTFULL = 456,
32         ERR_ACCEPTEXIST = 457,
33         ERR_ACCEPTNOT = 458,
34         ERR_TARGUMODEG = 716,
35         RPL_TARGNOTIFY = 717,
36         RPL_UMODEGMSG = 718
37 };
38
39 class callerid_data
40 {
41  public:
42         typedef insp::flat_set<User*> UserSet;
43         typedef std::vector<callerid_data*> CallerIdDataSet;
44
45         time_t lastnotify;
46
47         /** Users I accept messages from
48          */
49         UserSet accepting;
50
51         /** Users who list me as accepted
52          */
53         CallerIdDataSet wholistsme;
54
55         callerid_data() : lastnotify(0) { }
56
57         std::string ToString(SerializeFormat format) const
58         {
59                 std::ostringstream oss;
60                 oss << lastnotify;
61                 for (UserSet::const_iterator i = accepting.begin(); i != accepting.end(); ++i)
62                 {
63                         User* u = *i;
64                         // Encode UIDs.
65                         oss << "," << (format == FORMAT_USER ? u->nick : u->uuid);
66                 }
67                 return oss.str();
68         }
69 };
70
71 struct CallerIDExtInfo : public ExtensionItem
72 {
73         CallerIDExtInfo(Module* parent)
74                 : ExtensionItem("callerid_data", ExtensionItem::EXT_USER, parent)
75         {
76         }
77
78         std::string serialize(SerializeFormat format, const Extensible* container, void* item) const CXX11_OVERRIDE
79         {
80                 std::string ret;
81                 if (format != FORMAT_NETWORK)
82                 {
83                         callerid_data* dat = static_cast<callerid_data*>(item);
84                         ret = dat->ToString(format);
85                 }
86                 return ret;
87         }
88
89         void unserialize(SerializeFormat format, Extensible* container, const std::string& value) CXX11_OVERRIDE
90         {
91                 if (format == FORMAT_NETWORK)
92                         return;
93
94                 void* old = get_raw(container);
95                 if (old)
96                         this->free(NULL, old);
97                 callerid_data* dat = new callerid_data;
98                 set_raw(container, dat);
99
100                 irc::commasepstream s(value);
101                 std::string tok;
102                 if (s.GetToken(tok))
103                         dat->lastnotify = ConvToNum<time_t>(tok);
104
105                 while (s.GetToken(tok))
106                 {
107                         User *u = ServerInstance->FindNick(tok);
108                         if ((u) && (u->registered == REG_ALL) && (!u->quitting))
109                         {
110                                 if (dat->accepting.insert(u).second)
111                                 {
112                                         callerid_data* other = this->get(u, true);
113                                         other->wholistsme.push_back(dat);
114                                 }
115                         }
116                 }
117         }
118
119         callerid_data* get(User* user, bool create)
120         {
121                 callerid_data* dat = static_cast<callerid_data*>(get_raw(user));
122                 if (create && !dat)
123                 {
124                         dat = new callerid_data;
125                         set_raw(user, dat);
126                 }
127                 return dat;
128         }
129
130         void free(Extensible* container, void* item) CXX11_OVERRIDE
131         {
132                 callerid_data* dat = static_cast<callerid_data*>(item);
133
134                 // We need to walk the list of users on our accept list, and remove ourselves from their wholistsme.
135                 for (callerid_data::UserSet::iterator it = dat->accepting.begin(); it != dat->accepting.end(); ++it)
136                 {
137                         callerid_data *targ = this->get(*it, false);
138
139                         if (!targ)
140                         {
141                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (1)");
142                                 continue; // shouldn't happen, but oh well.
143                         }
144
145                         if (!stdalgo::vector::swaperase(targ->wholistsme, dat))
146                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (2)");
147                 }
148                 delete dat;
149         }
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))
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, unsigned int index) CXX11_OVERRIDE
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(User* user, const Params& parameters) CXX11_OVERRIDE
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(Numerics::NoSuchNick(tok));
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 Params& parameters) CXX11_OVERRIDE
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 (callerid_data::UserSet::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, InspIRCd::Format("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, whotoadd->nick, "is already on your accept list");
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, whotoremove->nick, "is not on your accept list");
303                         return false;
304                 }
305                 if (!dat->accepting.erase(whotoremove))
306                 {
307                         user->WriteNumeric(ERR_ACCEPTNOT, whotoremove->nick, "is not on your accept list");
308                         return false;
309                 }
310
311                 // Look up their list to remove me.
312                 callerid_data *dat2 = extInfo.get(whotoremove, false);
313                 if (!dat2)
314                 {
315                         // How the fuck is this possible.
316                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (3)");
317                         return false;
318                 }
319
320                 if (!stdalgo::vector::swaperase(dat2->wholistsme, dat))
321                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (4)");
322
323
324                 user->WriteNotice(whotoremove->nick + " is no longer on your accept list");
325                 return true;
326         }
327 };
328
329 class CallerIDAPIImpl : public CallerID::APIBase
330 {
331  private:
332         CallerIDExtInfo& ext;
333
334  public:
335         CallerIDAPIImpl(Module* Creator, CallerIDExtInfo& Ext)
336                 : CallerID::APIBase(Creator)
337                 , ext(Ext)
338         {
339         }
340
341         bool IsOnAcceptList(User* source, User* target) CXX11_OVERRIDE
342         {
343                 callerid_data* dat = ext.get(target, true);
344                 return dat->accepting.count(source);
345         }
346 };
347
348
349 class ModuleCallerID
350         : public Module
351         , public CTCTags::EventListener
352 {
353         CommandAccept cmd;
354         CallerIDAPIImpl api;
355         SimpleUserModeHandler myumode;
356
357         // Configuration variables:
358         bool tracknick; // Allow ACCEPT entries to update with nick changes.
359         unsigned int notify_cooldown; // Seconds between notifications.
360
361         /** Removes a user from all accept lists
362          * @param who The user to remove from accepts
363          */
364         void RemoveFromAllAccepts(User* who)
365         {
366                 // First, find the list of people who have me on accept
367                 callerid_data *userdata = cmd.extInfo.get(who, false);
368                 if (!userdata)
369                         return;
370
371                 // Iterate over the list of people who accept me, and remove all entries
372                 for (callerid_data::CallerIdDataSet::iterator it = userdata->wholistsme.begin(); it != userdata->wholistsme.end(); ++it)
373                 {
374                         callerid_data *dat = *(it);
375
376                         // Find me on their callerid list
377                         if (!dat->accepting.erase(who))
378                                 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "ERROR: Inconsistency detected in callerid state, please report (5)");
379                 }
380
381                 userdata->wholistsme.clear();
382         }
383
384 public:
385         ModuleCallerID()
386                 : CTCTags::EventListener(this)
387                 , cmd(this)
388                 , api(this, cmd.extInfo)
389                 , myumode(this, "callerid", 'g')
390         {
391         }
392
393         Version GetVersion() CXX11_OVERRIDE
394         {
395                 return Version("Implementation of callerid, provides user mode +g and the ACCEPT command", VF_COMMON | VF_VENDOR);
396         }
397
398         void On005Numeric(std::map<std::string, std::string>& tokens) CXX11_OVERRIDE
399         {
400                 tokens["ACCEPT"] = ConvToStr(cmd.maxaccepts);
401                 tokens["CALLERID"] = ConvToStr(myumode.GetModeChar());
402         }
403
404         ModResult HandleMessage(User* user, const MessageTarget& target)
405         {
406                 if (!IS_LOCAL(user) || target.type != MessageTarget::TYPE_USER)
407                         return MOD_RES_PASSTHRU;
408
409                 User* dest = target.Get<User>();
410                 if (!dest->IsModeSet(myumode) || (user == dest))
411                         return MOD_RES_PASSTHRU;
412
413                 if (user->HasPrivPermission("users/ignore-callerid"))
414                         return MOD_RES_PASSTHRU;
415
416                 callerid_data* dat = cmd.extInfo.get(dest, true);
417                 if (!dat->accepting.count(user))
418                 {
419                         time_t now = ServerInstance->Time();
420                         /* +g and *not* accepted */
421                         user->WriteNumeric(ERR_TARGUMODEG, dest->nick, "is in +g mode (server-side ignore).");
422                         if (now > (dat->lastnotify + (time_t)notify_cooldown))
423                         {
424                                 user->WriteNumeric(RPL_TARGNOTIFY, dest->nick, "has been informed that you messaged them.");
425                                 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 user mode +g set. Use /ACCEPT +%s to allow.",
426                                                 user->nick.c_str()));
427                                 dat->lastnotify = now;
428                         }
429                         return MOD_RES_DENY;
430                 }
431                 return MOD_RES_PASSTHRU;
432         }
433
434         ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details) CXX11_OVERRIDE
435         {
436                 return HandleMessage(user, target);
437         }
438
439         ModResult OnUserPreTagMessage(User* user, const MessageTarget& target, CTCTags::TagMessageDetails& details) CXX11_OVERRIDE
440         {
441                 return HandleMessage(user, target);
442         }
443
444         void OnUserPostNick(User* user, const std::string& oldnick) CXX11_OVERRIDE
445         {
446                 if (!tracknick)
447                         RemoveFromAllAccepts(user);
448         }
449
450         void OnUserQuit(User* user, const std::string& message, const std::string& oper_message) CXX11_OVERRIDE
451         {
452                 RemoveFromAllAccepts(user);
453         }
454
455         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
456         {
457                 ConfigTag* tag = ServerInstance->Config->ConfValue("callerid");
458                 cmd.maxaccepts = tag->getUInt("maxaccepts", 30);
459                 tracknick = tag->getBool("tracknick");
460                 notify_cooldown = tag->getDuration("cooldown", 60);
461         }
462
463         void Prioritize() CXX11_OVERRIDE
464         {
465                 // Want to be after modules like silence or services_account
466                 ServerInstance->Modules->SetPriority(this, I_OnUserPreMessage, PRIORITY_LAST);
467         }
468 };
469
470 MODULE_INIT(ModuleCallerID)