XMPP Mortuary blocks are now tagged with the user they represent, so if they delete...
[citadel.git] / citadel / modules / xmpp / xmpp_presence.c
1 /*
2  * Handle XMPP presence exchanges
3  *
4  * Copyright (c) 2007-2021 by Art Cancro and citadel.org
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include "sysdep.h"
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <pwd.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <assert.h>
32
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
35 # include <time.h>
36 #else
37 # if HAVE_SYS_TIME_H
38 #  include <sys/time.h>
39 # else
40 #  include <time.h>
41 # endif
42 #endif
43
44 #include <sys/wait.h>
45 #include <string.h>
46 #include <limits.h>
47 #include <ctype.h>
48 #include <expat.h>
49 #include <libcitadel.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "internet_addressing.h"
56 #include "ctdl_module.h"
57 #include "serv_xmpp.h"
58
59
60 /* 
61  * Indicate the presence of another user to the client
62  * (used in several places)
63  */
64 void xmpp_indicate_presence(char *presence_jid)
65 {
66         char xmlbuf[256];
67
68         syslog(LOG_DEBUG, "xmpp: indicating presence of <%s> to <%s>", presence_jid, XMPP->client_jid);
69         cprintf("<presence from=\"%s\" ", xmlesc(xmlbuf, presence_jid, sizeof xmlbuf));
70         cprintf("to=\"%s\"></presence>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
71 }
72
73
74 /*
75  * Convenience function to determine whether any given session is 'visible' to any other given session,
76  * and is capable of receiving instant messages from that session.
77  */
78 int xmpp_is_visible(struct CitContext *cptr, struct CitContext *to_whom) {
79         int aide = (to_whom->user.axlevel >= AxAideU);
80
81         if (    (cptr->logged_in)
82                 &&      (((cptr->cs_flags&CS_STEALTH)==0) || (aide))    /* aides see everyone */
83                 &&      (cptr->user.usernum != to_whom->user.usernum)   /* don't show myself */
84                 &&      (cptr->can_receive_im)                          /* IM-capable session */
85         ) {
86                 return(1);
87         }
88         else {
89                 return(0);
90         }
91 }
92
93
94 /* 
95  * Initial dump of the entire wholist
96  */
97 void xmpp_wholist_presence_dump(void)
98 {
99         struct CitContext *cptr = NULL;
100         int nContexts, i;
101         
102         cptr = CtdlGetContextArray(&nContexts);
103         if (!cptr) {
104                 return;
105         }
106
107         for (i=0; i<nContexts; i++) {
108                 if (xmpp_is_visible(&cptr[i], CC)) {
109                         xmpp_indicate_presence(cptr[i].cs_principal_id);
110                 }
111         }
112         free(cptr);
113 }
114
115
116 /*
117  * Function to remove a buddy subscription and delete from the roster
118  * (used in several places)
119  */
120 void xmpp_destroy_buddy(char *presence_jid, int aggressively) {
121         static int unsolicited_id = 1;
122         char xmlbuf1[256];
123         char xmlbuf2[256];
124
125         if (!presence_jid) return;
126         if (!XMPP) return;
127         if (!XMPP->client_jid) return;
128
129         /* Transmit non-presence information */
130         cprintf("<presence type=\"unavailable\" from=\"%s\" to=\"%s\"></presence>",
131                 xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1),
132                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2)
133         );
134
135         /*
136          * Setting the "aggressively" flag also sends an "unsubscribed" presence update.
137          * We only ask for this when flushing the client side roster, because if we do it
138          * in the middle of a session when another user logs off, some clients (Jitsi) interpret
139          * it as a rejection of a subscription request.
140          */
141         if (aggressively) {
142                 cprintf("<presence type=\"unsubscribed\" from=\"%s\" to=\"%s\"></presence>",
143                         xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1),
144                         xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2)
145                 );
146         }
147
148         // note: we should implement xmpp_indicate_nonpresence so we can use it elsewhere
149
150         /* Do an unsolicited roster update that deletes the contact. */
151         cprintf("<iq from=\"%s\" to=\"%s\" id=\"unbuddy_%x\" type=\"result\">",
152                 xmlesc(xmlbuf1, CC->cs_principal_id, sizeof xmlbuf1),
153                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2),
154                 ++unsolicited_id
155         );
156         cprintf("<query xmlns=\"jabber:iq:roster\">");
157         cprintf("<item jid=\"%s\" subscription=\"remove\">", xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1));
158         cprintf("<group>%s</group>", xmlesc(xmlbuf1, CtdlGetConfigStr("c_humannode"), sizeof xmlbuf1));
159         cprintf("</item>");
160         cprintf("</query>"
161                 "</iq>"
162         );
163 }
164
165
166 /*
167  * When a user logs in or out of the local Citadel system, notify all XMPP sessions about it.
168  * THIS FUNCTION HAS A BUG IN IT THAT ENUMERATES THE SESSIONS WRONG.
169  */
170 void xmpp_presence_notify(char *presence_jid, int event_type) {
171         struct CitContext *cptr;
172         static int unsolicited_id = 12345;
173         int visible_sessions = 0;
174         int nContexts, i;
175         int which_cptr_is_relevant = (-1);
176
177         if (IsEmptyStr(presence_jid)) return;
178         if (CC->kill_me) return;
179
180         cptr = CtdlGetContextArray(&nContexts);
181         if (!cptr) {
182                 return;
183         }
184
185         /* Count the visible sessions for this user */
186         for (i=0; i<nContexts; i++) {
187                 if ( (!strcasecmp(cptr[i].cs_principal_id, presence_jid))
188                    && (xmpp_is_visible(&cptr[i], CC))
189                 )  {
190                         ++visible_sessions;
191                         which_cptr_is_relevant = i;
192                 }
193         }
194
195         syslog(LOG_DEBUG, "xmpp: %d sessions for <%s> are now visible to session %d", visible_sessions, presence_jid, CC->cs_pid);
196
197         if ( (event_type == XMPP_EVT_LOGIN) && (visible_sessions == 1) ) {
198
199                 syslog(LOG_DEBUG, "xmpp: telling session %d that <%s> logged in", CC->cs_pid, presence_jid);
200
201                 /* Do an unsolicited roster update that adds a new contact. */
202                 assert(which_cptr_is_relevant >= 0);
203                 cprintf("<iq id=\"unsolicited_%x\" type=\"result\">", ++unsolicited_id);
204                 cprintf("<query xmlns=\"jabber:iq:roster\">");
205                 xmpp_roster_item(&cptr[which_cptr_is_relevant]);
206                 cprintf("</query></iq>");
207
208                 /* Transmit presence information */
209                 xmpp_indicate_presence(presence_jid);
210         }
211
212         if (visible_sessions == 0) {
213                 syslog(LOG_DEBUG, "xmpp: telling session %d that <%s> logged out", CC->cs_pid, presence_jid);
214                 xmpp_destroy_buddy(presence_jid, 0);    /* non aggressive presence update */
215         }
216
217         free(cptr);
218 }
219
220
221 void xmpp_fetch_mortuary_backend(long msgnum, void *userdata) {
222         HashList *mortuary = (HashList *) userdata;
223         struct CtdlMessage *msg;
224         char *ptr = NULL;
225         char *lasts = NULL;
226
227         msg = CtdlFetchMessage(msgnum, 1);
228         if (msg == NULL) {
229                 return;
230         }
231
232         /* now add anyone we find into the hashlist */
233
234         /* skip past the headers */
235         ptr = strstr(msg->cm_fields[eMesageText], "\n\n");
236         if (ptr != NULL) {
237                 ptr += 2;
238         }
239         else {
240                 ptr = strstr(msg->cm_fields[eMesageText], "\n\r\n");
241                 if (ptr != NULL) {
242                         ptr += 3;
243                 }
244         }
245
246         /* the remaining lines are addresses */
247         if (ptr != NULL) {
248                 ptr = strtok_r(ptr, "\n", &lasts);
249                 while (ptr != NULL) {
250                         char *pch = strdup(ptr);
251                         Put(mortuary, pch, strlen(pch), pch, NULL);
252                         ptr = strtok_r(NULL, "\n", &lasts);
253                 }
254         }
255
256         CM_Free(msg);
257 }
258
259
260 /*
261  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
262  * so we can remove them from any client's roster that still has them listed
263  */
264 HashList *xmpp_fetch_mortuary(void) {
265         HashList *mortuary = NewHash(1, NULL);
266         if (!mortuary) {
267                 syslog(LOG_ALERT, "xmpp: NewHash() failed!");
268                 return(NULL);
269         }
270
271         if (CtdlGetRoom(&CC->room, USERCONFIGROOM) != 0) {
272                 /* no config room exists - no further processing is required. */
273                 return(mortuary);
274         }
275         CtdlForEachMessage(MSGS_LAST, 1, NULL, XMPPMORTUARY, NULL,
276                 xmpp_fetch_mortuary_backend, (void *)mortuary );
277
278         return(mortuary);
279 }
280
281
282 /*
283  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
284  * so we can remove them from any client's roster that still has them listed
285  */
286 void xmpp_store_mortuary(HashList *mortuary) {
287         HashPos *HashPos;
288         long len;
289         void *Value;
290         const char *Key;
291         StrBuf *themsg;
292
293         themsg = NewStrBuf();
294         StrBufPrintf(themsg,    "Content-type: " XMPPMORTUARY "\n"
295                                 "Content-transfer-encoding: 7bit\n"
296                                 "\n"
297         );
298
299         HashPos = GetNewHashPos(mortuary, 0);
300         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
301         {
302                 StrBufAppendPrintf(themsg, "%s\n", (char *)Value);
303         }
304         DeleteHashPos(&HashPos);
305
306         /* Delete the old mortuary */
307         CtdlDeleteMessages(USERCONFIGROOM, NULL, 0, XMPPMORTUARY);
308
309         /* And save the new one to disk */
310         quickie_message(CC->user.fullname, NULL, NULL, USERCONFIGROOM, ChrPtr(themsg), 4, "XMPP Mortuary");
311         FreeStrBuf(&themsg);
312 }
313
314
315 /*
316  * Upon logout we make an attempt to delete the whole roster, in order to
317  * try to keep "ghost" buddies from remaining in the client-side roster.
318  *
319  * Since the client is probably not still alive, also remember the current
320  * roster for next time so we can delete dead buddies then.
321  */
322 void xmpp_massacre_roster(void)
323 {
324         struct CitContext *cptr;
325         int nContexts, i;
326         HashList *mortuary = xmpp_fetch_mortuary();
327
328         cptr = CtdlGetContextArray(&nContexts);
329         if (cptr) {
330                 for (i=0; i<nContexts; i++) {
331                         if (xmpp_is_visible(&cptr[i], CC)) {
332                                 if (mortuary) {
333                                         char *buddy = strdup(cptr[i].cs_principal_id);
334                                         Put(mortuary, buddy, strlen(buddy), buddy, NULL);
335                                 }
336                         }
337                 }
338                 free (cptr);
339         }
340
341         if (mortuary) {
342                 xmpp_store_mortuary(mortuary);
343                 DeleteHash(&mortuary);
344         }
345 }
346
347
348 /*
349  * Stupidly, XMPP does not specify a way to tell the client to flush its client-side roster
350  * and prepare to receive a new one.  So instead we remember every buddy we've ever told the
351  * client about, and push delete operations out at the beginning of a session.
352  * 
353  * We omit any users who happen to be online right now, but we still keep them in the mortuary,
354  * which needs to be maintained as a list of every buddy the user has ever seen.  We don't know
355  * when they're connecting from the same client and when they're connecting from a different client,
356  * so we have no guarantee of what is in the client side roster at connect time.
357  */
358 void xmpp_delete_old_buddies_who_no_longer_exist_from_the_client_roster(void)
359 {
360         long len;
361         void *Value;
362         const char *Key;
363         struct CitContext *cptr;
364         int nContexts, i;
365         int online_now = 0;
366         HashList *mortuary = xmpp_fetch_mortuary();
367         HashPos *HashPos = GetNewHashPos(mortuary, 0);
368
369         /* we need to omit anyone who is currently online */
370         cptr = CtdlGetContextArray(&nContexts);
371
372         /* go through the list of users in the mortuary... */
373         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
374         {
375
376                 online_now = 0;
377                 if (cptr) for (i=0; i<nContexts; i++) {
378                         if (xmpp_is_visible(&cptr[i], CC)) {
379                                 if (!strcasecmp(cptr[i].cs_principal_id, (char *)Value)) {
380                                         online_now = 1;
381                                 }
382                         }
383                 }
384
385                 if (!online_now) {
386                         xmpp_destroy_buddy((char *)Value, 1);   /* aggressive presence update */
387                 }
388
389         }
390         DeleteHashPos(&HashPos);
391         DeleteHash(&mortuary);
392         free(cptr);
393 }