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