Merge branch 'master' of ssh://git.citadel.org/appl/gitroot/citadel
[citadel.git] / citadel / modules / xmpp / xmpp_presence.c
1 /*
2  * Handle XMPP presence exchanges
3  *
4  * Copyright (c) 2007-2010 by Art Cancro
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 /* 
63  * Indicate the presence of another user to the client
64  * (used in several places)
65  */
66 void xmpp_indicate_presence(char *presence_jid)
67 {
68         char xmlbuf[256];
69
70 <<<<<<< HEAD
71         syslog(LOG_DEBUG, "XMPP: indicating presence of <%s> to <%s>", presence_jid, XMPP->client_jid);
72 =======
73 >>>>>>> 1c0b8162b0a90f2e97028a531005c11b09441498
74         cprintf("<presence from=\"%s\" ", xmlesc(xmlbuf, presence_jid, sizeof xmlbuf));
75         cprintf("to=\"%s\"></presence>", xmlesc(xmlbuf, XMPP->client_jid, sizeof xmlbuf));
76 }
77
78
79
80 /*
81  * Convenience function to determine whether any given session is 'visible' to any other given session,
82  * and is capable of receiving instant messages from that session.
83  */
84 int xmpp_is_visible(struct CitContext *cptr, struct CitContext *to_whom) {
85         int aide = (to_whom->user.axlevel >= AxAideU);
86
87         if (    (cptr->logged_in)
88                 &&      (((cptr->cs_flags&CS_STEALTH)==0) || (aide))    /* aides see everyone */
89                 &&      (cptr->user.usernum != to_whom->user.usernum)   /* don't show myself */
90                 &&      (cptr->can_receive_im)                          /* IM-capable session */
91         ) {
92                 return(1);
93         }
94         else {
95                 return(0);
96         }
97 }
98
99
100 /* 
101  * Initial dump of the entire wholist
102  */
103 void xmpp_wholist_presence_dump(void)
104 {
105         struct CitContext *cptr = NULL;
106         int nContexts, i;
107         
108         cptr = CtdlGetContextArray(&nContexts);
109         if (!cptr) {
110                 return;
111         }
112
113         for (i=0; i<nContexts; i++) {
114                 if (xmpp_is_visible(&cptr[i], CC)) {
115                         xmpp_indicate_presence(cptr[i].cs_inet_email);
116                 }
117         }
118         free(cptr);
119 }
120
121
122 /*
123  * Function to remove a buddy subscription and delete from the roster
124  * (used in several places)
125  */
126 void xmpp_destroy_buddy(char *presence_jid, int aggressively) {
127         static int unsolicited_id = 1;
128         char xmlbuf1[256];
129         char xmlbuf2[256];
130
131         if (!presence_jid) return;
132         if (!XMPP) return;
133         if (!XMPP->client_jid) return;
134
135         /* Transmit non-presence information */
136         cprintf("<presence type=\"unavailable\" from=\"%s\" to=\"%s\"></presence>",
137                 xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1),
138                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2)
139         );
140
141         /*
142          * Setting the "aggressively" flag also sends an "unsubscribed" presence update.
143          * We only ask for this when flushing the client side roster, because if we do it
144          * in the middle of a session when another user logs off, some clients (Jitsi) interpret
145          * it as a rejection of a subscription request.
146          */
147         if (aggressively) {
148                 cprintf("<presence type=\"unsubscribed\" from=\"%s\" to=\"%s\"></presence>",
149                         xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1),
150                         xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2)
151                 );
152         }
153
154         // FIXME ... we should implement xmpp_indicate_nonpresence so we can use it elsewhere
155
156         /* Do an unsolicited roster update that deletes the contact. */
157         cprintf("<iq from=\"%s\" to=\"%s\" id=\"unbuddy_%x\" type=\"result\">",
158                 xmlesc(xmlbuf1, CC->cs_inet_email, sizeof xmlbuf1),
159                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2),
160                 ++unsolicited_id
161         );
162         cprintf("<query xmlns=\"jabber:iq:roster\">");
163         cprintf("<item jid=\"%s\" subscription=\"remove\">", xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1));
164         cprintf("<group>%s</group>", xmlesc(xmlbuf1, config.c_humannode, sizeof xmlbuf1));
165         cprintf("</item>");
166         cprintf("</query>"
167                 "</iq>"
168         );
169 }
170
171
172 /*
173  * When a user logs in or out of the local Citadel system, notify all XMPP sessions about it.
174  * THIS FUNCTION HAS A BUG IN IT THAT ENUMERATES THE SESSIONS WRONG.
175  */
176 void xmpp_presence_notify(char *presence_jid, int event_type) {
177         struct CitContext *cptr;
178         static int unsolicited_id = 12345;
179         int visible_sessions = 0;
180         int nContexts, i;
181         int which_cptr_is_relevant = (-1);
182
183         if (IsEmptyStr(presence_jid)) return;
184         if (CC->kill_me) return;
185
186         cptr = CtdlGetContextArray(&nContexts);
187         if (!cptr) {
188                 return;
189         }
190
191         /* Count the visible sessions for this user */
192         for (i=0; i<nContexts; i++) {
193                 if ( (!strcasecmp(cptr[i].cs_inet_email, presence_jid))
194                    && (xmpp_is_visible(&cptr[i], CC))
195                 )  {
196                         ++visible_sessions;
197                         which_cptr_is_relevant = i;
198                 }
199         }
200
201         syslog(LOG_DEBUG, "%d sessions for <%s> are now visible to session %d\n", visible_sessions, presence_jid, CC->cs_pid);
202
203         if ( (event_type == XMPP_EVT_LOGIN) && (visible_sessions == 1) ) {
204
205                 syslog(LOG_DEBUG, "Telling session %d that <%s> logged in\n", 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                 syslog(LOG_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[eMesageText], "\n\n");
244         if (ptr != NULL) {
245                 ptr += 2;
246         }
247         else {
248                 ptr = strstr(msg->cm_fields[eMesageText], "\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         CM_Free(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                 syslog(LOG_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