* Ok, it's not an async bug. When I changed everything over to xmpp_is_visible(...
[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
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <sys/wait.h>
46 #include <string.h>
47 #include <limits.h>
48 #include <ctype.h>
49 #include <expat.h>
50 #include <libcitadel.h>
51 #include "citadel.h"
52 #include "server.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "internet_addressing.h"
57 #include "md5.h"
58 #include "ctdl_module.h"
59 #include "serv_xmpp.h"
60
61
62
63 /* 
64  * Indicate the presence of another user to the client
65  * (used in several places)
66  */
67 void xmpp_indicate_presence(char *presence_jid)
68 {
69         cprintf("<presence from=\"%s\" to=\"%s\"></presence>",
70                 presence_jid,
71                 XMPP->client_jid
72         );
73 }
74
75
76
77 /*
78  * Convenience function to determine whether any given session is 'visible' to any other given session,
79  * and is capable of receiving instant messages from that session.
80  */
81 int xmpp_is_visible(struct CitContext *cptr, struct CitContext *to_whom) {
82         int aide = (to_whom->user.axlevel >= AxAideU);
83
84         if (    (cptr->logged_in)
85                 &&      (((cptr->cs_flags&CS_STEALTH)==0) || (aide))    /* aides see everyone */
86                 &&      (cptr->user.usernum != to_whom->user.usernum)   /* don't show myself */
87                 &&      (cptr->can_receive_im)                          /* IM-capable session */
88         ) {
89                 return(1);
90         }
91         else {
92                 return(0);
93         }
94 }
95
96
97 /* 
98  * Initial dump of the entire wholist
99  */
100 void xmpp_wholist_presence_dump(void)
101 {
102         struct CitContext *cptr = NULL;
103         int nContexts, i;
104         
105         cptr = CtdlGetContextArray(&nContexts);
106         if (!cptr) {
107                 return;
108         }
109
110         for (i=0; i<nContexts; i++) {
111                 if (xmpp_is_visible(&cptr[i], CC)) {
112                         xmpp_indicate_presence(cptr[i].cs_inet_email);
113                 }
114         }
115         free(cptr);
116 }
117
118
119 /*
120  * Function to remove a buddy subscription and delete from the roster
121  * (used in several places)
122  */
123 void xmpp_destroy_buddy(char *presence_jid) {
124         static int unsolicited_id = 1;
125
126         if (!presence_jid) return;
127         if (!XMPP) return;
128         if (!XMPP->client_jid) return;
129
130         CtdlLogPrintf(CTDL_DEBUG, "\033[31mdestroy_buddy(%s)\033[0m\n", presence_jid);
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
166         if (IsEmptyStr(presence_jid)) return;
167         if (CC->kill_me) return;
168
169         cptr = CtdlGetContextArray(&nContexts);
170         if (!cptr) {
171                 return;
172         }
173
174         /* Count the visible sessions for this user */
175         for (i=0; i<nContexts; i++) {
176                 if (xmpp_is_visible(CC, &cptr[i])) {
177                         ++visible_sessions;
178                 }
179         }
180
181         CtdlLogPrintf(CTDL_DEBUG, "%d sessions for <%s> are now visible to session %d\n",
182                 visible_sessions, presence_jid, CC->cs_pid);
183
184         if ( (event_type == XMPP_EVT_LOGIN) && (visible_sessions == 1) ) {
185
186                 CtdlLogPrintf(CTDL_DEBUG, "Telling session %d that <%s> logged in\n", CC->cs_pid, presence_jid);
187
188                 /* Do an unsolicited roster update that adds a new contact. */
189                 for (i=0; i<nContexts; i++) {
190                         if (xmpp_is_visible(CC, &cptr[i])) {
191                                 if (!strcasecmp(cptr[i].cs_inet_email, presence_jid)) {
192                                         cprintf("<iq id=\"unsolicited_%x\" type=\"result\">",
193                                                 ++unsolicited_id);
194                                         cprintf("<query xmlns=\"jabber:iq:roster\">");
195                                         xmpp_roster_item(&cptr[i]);
196                                         cprintf("</query>"
197                                                 "</iq>");
198                                 }
199                         }
200                 }
201
202                 /* Transmit presence information */
203                 xmpp_indicate_presence(presence_jid);
204         }
205
206         if (visible_sessions == 0) {
207                 CtdlLogPrintf(CTDL_DEBUG, "Telling session %d that <%s> logged out\n", CC->cs_pid, presence_jid);
208
209                 xmpp_destroy_buddy(presence_jid);
210         }
211         free(cptr);
212 }
213
214
215
216 void xmpp_fetch_mortuary_backend(long msgnum, void *userdata) {
217         HashList *mortuary = (HashList *) userdata;
218         struct CtdlMessage *msg;
219         char *ptr = NULL;
220         char *lasts = NULL;
221
222         msg = CtdlFetchMessage(msgnum, 1);
223         if (msg == NULL) {
224                 return;
225         }
226
227         /* now add anyone we find into the hashlist */
228
229         /* skip past the headers */
230         ptr = strstr(msg->cm_fields['M'], "\n\n");
231         if (ptr != NULL) {
232                 ptr += 2;
233         }
234         else {
235                 ptr = strstr(msg->cm_fields['M'], "\n\r\n");
236                 if (ptr != NULL) {
237                         ptr += 3;
238                 }
239         }
240
241         /* the remaining lines are addresses */
242         if (ptr != NULL) {
243                 ptr = strtok_r(ptr, "\n", &lasts);
244                 while (ptr != NULL) {
245                         char *pch = strdup(ptr);
246                         Put(mortuary, pch, strlen(pch), pch, NULL);
247                         ptr = strtok_r(NULL, "\n", &lasts);
248                 }
249         }
250
251         CtdlFreeMessage(msg);
252 }
253
254
255
256 /*
257  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
258  * so we can remove them from any client's roster that still has them listed
259  */
260 HashList *xmpp_fetch_mortuary(void) {
261         HashList *mortuary = NewHash(1, NULL);
262         if (!mortuary) {
263                 CtdlLogPrintf(CTDL_ALERT, "NewHash() failed!\n");
264                 return(NULL);
265         }
266
267         if (CtdlGetRoom(&CC->room, USERCONFIGROOM) != 0) {
268                 /* no config room exists - no further processing is required. */
269                 return(mortuary);
270         }
271         CtdlForEachMessage(MSGS_LAST, 1, NULL, XMPPMORTUARY, NULL,
272                 xmpp_fetch_mortuary_backend, (void *)mortuary );
273
274         return(mortuary);
275 }
276
277
278
279 /*
280  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
281  * so we can remove them from any client's roster that still has them listed
282  */
283 void xmpp_store_mortuary(HashList *mortuary) {
284         HashPos *HashPos;
285         long len;
286         void *Value;
287         const char *Key;
288         StrBuf *themsg;
289
290         themsg = NewStrBuf();
291         StrBufPrintf(themsg,    "Content-type: " XMPPMORTUARY "\n"
292                                 "Content-transfer-encoding: 7bit\n"
293                                 "\n"
294         );
295
296         HashPos = GetNewHashPos(mortuary, 0);
297         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
298         {
299                 StrBufAppendPrintf(themsg, "%s\n", (char *)Value);
300         }
301         DeleteHashPos(&HashPos);
302
303         /* Delete the old mortuary */
304         CtdlDeleteMessages(USERCONFIGROOM, NULL, 0, XMPPMORTUARY);
305
306         /* And save the new one to disk */
307         quickie_message("Citadel", NULL, NULL, USERCONFIGROOM, ChrPtr(themsg), 4, "XMPP Mortuary");
308         FreeStrBuf(&themsg);
309 }
310
311
312
313 /*
314  * Upon logout we make an attempt to delete the whole roster, in order to
315  * try to keep "ghost" buddies from remaining in the client-side roster.
316  *
317  * Since the client is probably not still alive, also remember the current
318  * roster for next time so we can delete dead buddies then.
319  */
320 void xmpp_massacre_roster(void)
321 {
322         struct CitContext *cptr;
323         int nContexts, i;
324         HashList *mortuary = xmpp_fetch_mortuary();
325
326         cptr = CtdlGetContextArray(&nContexts);
327         if (cptr) {
328                 for (i=0; i<nContexts; i++) {
329                         if (xmpp_is_visible(&cptr[i], CC)) {
330                                 if (mortuary) {
331                                         char *buddy = strdup(cptr[i].cs_inet_email);
332                                         Put(mortuary, buddy, strlen(buddy), buddy, NULL);
333                                 }
334                         }
335                 }
336                 free (cptr);
337         }
338
339         if (mortuary) {
340                 xmpp_store_mortuary(mortuary);
341                 DeleteHash(&mortuary);
342         }
343 }
344
345
346
347 /*
348  * Stupidly, XMPP does not specify a way to tell the client to flush its client-side roster
349  * and prepare to receive a new one.  So instead we remember every buddy we've ever told the
350  * client about, and push delete operations out at the beginning of a session.
351  * 
352  * We omit any users who happen to be online right now, but we still keep them in the mortuary,
353  * which needs to be maintained as a list of every buddy the user has ever seen.  We don't know
354  * when they're connecting from the same client and when they're connecting from a different client,
355  * so we have no guarantee of what is in the client side roster at connect time.
356  */
357 void xmpp_delete_old_buddies_who_no_longer_exist_from_the_client_roster(void)
358 {
359         long len;
360         void *Value;
361         const char *Key;
362         struct CitContext *cptr;
363         int nContexts, i;
364         int online_now = 0;
365         HashList *mortuary = xmpp_fetch_mortuary();
366         HashPos *HashPos = GetNewHashPos(mortuary, 0);
367
368         /* we need to omit anyone who is currently online */
369         cptr = CtdlGetContextArray(&nContexts);
370
371         /* go through the list of users in the mortuary... */
372         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
373         {
374
375                 online_now = 0;
376                 if (cptr) for (i=0; i<nContexts; i++) {
377                         if (xmpp_is_visible(&cptr[i], CC)) {
378                                 if (!strcasecmp(cptr[i].cs_inet_email, (char *)Value)) {
379                                         online_now = 1;
380                                 }
381                         }
382                 }
383
384                 if (!online_now) {
385                         xmpp_destroy_buddy((char *)Value);
386                 }
387
388         }
389         DeleteHashPos(&HashPos);
390         DeleteHash(&mortuary);
391         free(cptr);
392 }
393