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