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