2866daa97c1a432440dd0c31eb18e17abf26c614
[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) {
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         cprintf("<presence type=\"unsubscribed\" from=\"%s\" to=\"%s\"></presence>",
139                 xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1),
140                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2)
141         );
142         // FIXME ... we should implement xmpp_indicate_nonpresence so we can use it elsewhere
143
144         /* Do an unsolicited roster update that deletes the contact. */
145         cprintf("<iq from=\"%s\" to=\"%s\" id=\"unbuddy_%x\" type=\"result\">",
146                 xmlesc(xmlbuf1, CC->cs_inet_email, sizeof xmlbuf1),
147                 xmlesc(xmlbuf2, XMPP->client_jid, sizeof xmlbuf2),
148                 ++unsolicited_id
149         );
150         cprintf("<query xmlns=\"jabber:iq:roster\">");
151         cprintf("<item jid=\"%s\" subscription=\"remove\">", xmlesc(xmlbuf1, presence_jid, sizeof xmlbuf1));
152         cprintf("<group>%s</group>", xmlesc(xmlbuf1, config.c_humannode, sizeof xmlbuf1));
153         cprintf("</item>");
154         cprintf("</query>"
155                 "</iq>"
156         );
157 }
158
159
160 /*
161  * When a user logs in or out of the local Citadel system, notify all XMPP sessions about it.
162  * THIS FUNCTION HAS A BUG IN IT THAT ENUMERATES THE SESSIONS WRONG.
163  */
164 void xmpp_presence_notify(char *presence_jid, int event_type) {
165         struct CitContext *cptr;
166         static int unsolicited_id;
167         int visible_sessions = 0;
168         int nContexts, i;
169         int which_cptr_is_relevant = (-1);
170
171         if (IsEmptyStr(presence_jid)) return;
172         if (CC->kill_me) return;
173
174         cptr = CtdlGetContextArray(&nContexts);
175         if (!cptr) {
176                 return;
177         }
178
179         /* Count the visible sessions for this user */
180         for (i=0; i<nContexts; i++) {
181                 if ( (!strcasecmp(cptr[i].cs_inet_email, presence_jid))
182                    && (xmpp_is_visible(&cptr[i], CC))
183                 )  {
184                         ++visible_sessions;
185                         which_cptr_is_relevant = i;
186                 }
187         }
188
189         CtdlLogPrintf(CTDL_DEBUG, "%d sessions for <%s> are now visible to session %d\n",
190                 visible_sessions, presence_jid, CC->cs_pid);
191
192         if ( (event_type == XMPP_EVT_LOGIN) && (visible_sessions == 1) ) {
193
194                 CtdlLogPrintf(CTDL_DEBUG, "Telling session %d that <%s> logged in\n",
195                         CC->cs_pid, presence_jid);
196
197                 /* Do an unsolicited roster update that adds a new contact. */
198                 assert(which_cptr_is_relevant >= 0);
199                 cprintf("<iq id=\"unsolicited_%x\" type=\"result\">", ++unsolicited_id);
200                 cprintf("<query xmlns=\"jabber:iq:roster\">");
201                 xmpp_roster_item(&cptr[which_cptr_is_relevant]);
202                 cprintf("</query></iq>");
203
204                 /* Transmit presence information */
205                 xmpp_indicate_presence(presence_jid);
206         }
207
208         if (visible_sessions == 0) {
209                 CtdlLogPrintf(CTDL_DEBUG, "Telling session %d that <%s> logged out\n",
210                         CC->cs_pid, presence_jid);
211                 xmpp_destroy_buddy(presence_jid);
212         }
213
214         free(cptr);
215 }
216
217
218
219 void xmpp_fetch_mortuary_backend(long msgnum, void *userdata) {
220         HashList *mortuary = (HashList *) userdata;
221         struct CtdlMessage *msg;
222         char *ptr = NULL;
223         char *lasts = NULL;
224
225         msg = CtdlFetchMessage(msgnum, 1);
226         if (msg == NULL) {
227                 return;
228         }
229
230         /* now add anyone we find into the hashlist */
231
232         /* skip past the headers */
233         ptr = strstr(msg->cm_fields['M'], "\n\n");
234         if (ptr != NULL) {
235                 ptr += 2;
236         }
237         else {
238                 ptr = strstr(msg->cm_fields['M'], "\n\r\n");
239                 if (ptr != NULL) {
240                         ptr += 3;
241                 }
242         }
243
244         /* the remaining lines are addresses */
245         if (ptr != NULL) {
246                 ptr = strtok_r(ptr, "\n", &lasts);
247                 while (ptr != NULL) {
248                         char *pch = strdup(ptr);
249                         Put(mortuary, pch, strlen(pch), pch, NULL);
250                         ptr = strtok_r(NULL, "\n", &lasts);
251                 }
252         }
253
254         CtdlFreeMessage(msg);
255 }
256
257
258
259 /*
260  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
261  * so we can remove them from any client's roster that still has them listed
262  */
263 HashList *xmpp_fetch_mortuary(void) {
264         HashList *mortuary = NewHash(1, NULL);
265         if (!mortuary) {
266                 CtdlLogPrintf(CTDL_ALERT, "NewHash() failed!\n");
267                 return(NULL);
268         }
269
270         if (CtdlGetRoom(&CC->room, USERCONFIGROOM) != 0) {
271                 /* no config room exists - no further processing is required. */
272                 return(mortuary);
273         }
274         CtdlForEachMessage(MSGS_LAST, 1, NULL, XMPPMORTUARY, NULL,
275                 xmpp_fetch_mortuary_backend, (void *)mortuary );
276
277         return(mortuary);
278 }
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         /* FIXME temp crap 
307         StrBufAppendPrintf(themsg, "foo@bar.com\n");
308         StrBufAppendPrintf(themsg, "baz@quux.com\n");
309         StrBufAppendPrintf(themsg, "haha%c\n", 1);
310         StrBufAppendPrintf(themsg, "baaaz@quux.com\n");
311         StrBufAppendPrintf(themsg, "baaaz@quuuuuux.com\n");
312         */
313
314         /* Delete the old mortuary */
315         CtdlDeleteMessages(USERCONFIGROOM, NULL, 0, XMPPMORTUARY);
316
317         /* And save the new one to disk */
318         quickie_message("Citadel", NULL, NULL, USERCONFIGROOM, ChrPtr(themsg), 4, "XMPP Mortuary");
319         FreeStrBuf(&themsg);
320 }
321
322
323
324 /*
325  * Upon logout we make an attempt to delete the whole roster, in order to
326  * try to keep "ghost" buddies from remaining in the client-side roster.
327  *
328  * Since the client is probably not still alive, also remember the current
329  * roster for next time so we can delete dead buddies then.
330  */
331 void xmpp_massacre_roster(void)
332 {
333         struct CitContext *cptr;
334         int nContexts, i;
335         HashList *mortuary = xmpp_fetch_mortuary();
336
337         cptr = CtdlGetContextArray(&nContexts);
338         if (cptr) {
339                 for (i=0; i<nContexts; i++) {
340                         if (xmpp_is_visible(&cptr[i], CC)) {
341                                 if (mortuary) {
342                                         char *buddy = strdup(cptr[i].cs_inet_email);
343                                         Put(mortuary, buddy, strlen(buddy), buddy, NULL);
344                                 }
345                         }
346                 }
347                 free (cptr);
348         }
349
350         if (mortuary) {
351                 xmpp_store_mortuary(mortuary);
352                 DeleteHash(&mortuary);
353         }
354 }
355
356
357
358 /*
359  * Stupidly, XMPP does not specify a way to tell the client to flush its client-side roster
360  * and prepare to receive a new one.  So instead we remember every buddy we've ever told the
361  * client about, and push delete operations out at the beginning of a session.
362  * 
363  * We omit any users who happen to be online right now, but we still keep them in the mortuary,
364  * which needs to be maintained as a list of every buddy the user has ever seen.  We don't know
365  * when they're connecting from the same client and when they're connecting from a different client,
366  * so we have no guarantee of what is in the client side roster at connect time.
367  */
368 void xmpp_delete_old_buddies_who_no_longer_exist_from_the_client_roster(void)
369 {
370         long len;
371         void *Value;
372         const char *Key;
373         struct CitContext *cptr;
374         int nContexts, i;
375         int online_now = 0;
376         HashList *mortuary = xmpp_fetch_mortuary();
377         HashPos *HashPos = GetNewHashPos(mortuary, 0);
378
379         /* we need to omit anyone who is currently online */
380         cptr = CtdlGetContextArray(&nContexts);
381
382         /* go through the list of users in the mortuary... */
383         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
384         {
385
386                 online_now = 0;
387                 if (cptr) for (i=0; i<nContexts; i++) {
388                         if (xmpp_is_visible(&cptr[i], CC)) {
389                                 if (!strcasecmp(cptr[i].cs_inet_email, (char *)Value)) {
390                                         online_now = 1;
391                                 }
392                         }
393                 }
394
395                 if (!online_now) {
396                         xmpp_destroy_buddy((char *)Value);
397                 }
398
399         }
400         DeleteHashPos(&HashPos);
401         DeleteHash(&mortuary);
402         free(cptr);
403 }
404