9191f8f65561b413cc28c4b7e2938e360be6f105
[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         XPrint(HKEY("presence"),
69                XPROPERTY("from", presence_jid, strlen(presence_jid)),
70                XPROPERTY("to",  XMPP->client_jid, strlen(XMPP->client_jid)),
71                TYPE_ARGEND);
72 }
73
74
75
76 /*
77  * Convenience function to determine whether any given session is 'visible' to any other given session,
78  * and is capable of receiving instant messages from that session.
79  */
80 int xmpp_is_visible(struct CitContext *cptr, struct CitContext *to_whom) {
81         int aide = (to_whom->user.axlevel >= AxAideU);
82
83         if (    (cptr->logged_in)
84                 &&      (((cptr->cs_flags&CS_STEALTH)==0) || (aide))    /* aides see everyone */
85                 &&      (cptr->user.usernum != to_whom->user.usernum)   /* don't show myself */
86                 &&      (cptr->can_receive_im)                          /* IM-capable session */
87         ) {
88                 return(1);
89         }
90         else {
91                 return(0);
92         }
93 }
94
95
96 /* 
97  * Initial dump of the entire wholist
98  * Respond to a <presence> update by firing back with presence information
99  * on the entire wholist.  Check this assumption, it's probably wrong.   
100  */
101 void xmpp_wholist_presence_dump(void *data, const char *supplied_el, const char **attr)
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         struct CitContext *CCC = CC;
127         char Buf[64];
128         long blen;
129
130         if (!presence_jid) return;
131         if (!XMPP) return;
132         if (!XMPP->client_jid) return;
133
134         /* Transmit non-presence information */
135         XPrint(HKEY("presence"), XCLOSED,
136                XCPROPERTY("type", "unavailable"),
137                XPROPERTY("from", presence_jid, strlen(presence_jid)),
138                XPROPERTY("to",  XMPP->client_jid, strlen(XMPP->client_jid)),
139                TYPE_ARGEND);
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                 XPrint(HKEY("presence"), XCLOSED,
149                        XCPROPERTY("type", "unsubscribed"),
150                        XPROPERTY("from", presence_jid, strlen(presence_jid)),
151                        XPROPERTY("to",  XMPP->client_jid, strlen(XMPP->client_jid)),
152                        TYPE_ARGEND);
153         }
154
155         // FIXME ... we should implement xmpp_indicate_nonpresence so we can use it elsewhere
156
157         blen = snprintf(Buf, sizeof(Buf), "unbuddy_%x", ++unsolicited_id);
158
159         /* Do an unsolicited roster update that deletes the contact. */
160         XPrint(HKEY("iq"), 0,
161                XCPROPERTY("type", "result"),
162                XPROPERTY("from", CCC->cs_inet_email, strlen(CCC->cs_inet_email)),
163                XPROPERTY("to",  XMPP->client_jid, strlen(XMPP->client_jid)),
164                XPROPERTY("id",  Buf, blen),
165                TYPE_ARGEND);
166
167         XPrint(HKEY("query"), 0,
168                XCPROPERTY("xmlns", "jabber:iq:roster"),
169                TYPE_ARGEND);
170
171         XPrint(HKEY("item"), 0,
172                XCPROPERTY("subscription", "remove"),
173                XPROPERTY("jid", presence_jid, strlen(presence_jid)),
174                TYPE_ARGEND);
175
176         XPrint(HKEY("group"), XCLOSED,
177                XCFGBODY(c_humannode),
178                TYPE_ARGEND);
179         XPUT("</item>"
180              "</query>"
181              "</iq>"
182         );
183 }
184
185
186 /*
187  * When a user logs in or out of the local Citadel system, notify all XMPP sessions about it.
188  * THIS FUNCTION HAS A BUG IN IT THAT ENUMERATES THE SESSIONS WRONG.
189  */
190 void xmpp_presence_notify(char *presence_jid, int event_type) {
191         struct CitContext *cptr;
192         static int unsolicited_id;
193         int visible_sessions = 0;
194         int nContexts, i;
195         int which_cptr_is_relevant = (-1);
196
197         if (IsEmptyStr(presence_jid)) return;
198         if (CC->kill_me) return;
199
200         cptr = CtdlGetContextArray(&nContexts);
201         if (!cptr) {
202                 return;
203         }
204
205         /* Count the visible sessions for this user */
206         for (i=0; i<nContexts; i++) {
207                 if ( (!strcasecmp(cptr[i].cs_inet_email, presence_jid))
208                    && (xmpp_is_visible(&cptr[i], CC))
209                 )  {
210                         ++visible_sessions;
211                         which_cptr_is_relevant = i;
212                 }
213         }
214
215         XMPP_syslog(LOG_DEBUG, "%d sessions for <%s> are now visible to session %d\n",
216                     visible_sessions, presence_jid, CC->cs_pid);
217
218         if ( (event_type == XMPP_EVT_LOGIN) && (visible_sessions == 1) ) {
219                 long blen;
220                 char Buf[64];
221
222                 XMPP_syslog(LOG_DEBUG, "Telling session %d that <%s> logged in\n",
223                             CC->cs_pid, presence_jid);
224
225                 /* Do an unsolicited roster update that adds a new contact. */
226                 assert(which_cptr_is_relevant >= 0);
227
228                 blen = snprintf(Buf, sizeof(Buf), "unsolicited_%x", ++unsolicited_id);
229
230                 XPrint(HKEY("iq"), 0,
231                        XCPROPERTY("type", "result"),
232                        XPROPERTY("id", Buf, blen),
233                        TYPE_ARGEND);
234
235                 XPrint(HKEY("query"), 0,
236                        XCPROPERTY("xmlns", "jabber:iq:roster"),
237                        TYPE_ARGEND);
238
239                 xmpp_roster_item(&cptr[which_cptr_is_relevant]);
240                 XPUT("</query></iq>");
241
242                 /* Transmit presence information */
243                 xmpp_indicate_presence(presence_jid);
244         }
245
246         if (visible_sessions == 0) {
247                 XMPP_syslog(LOG_DEBUG, "Telling session %d that <%s> logged out\n",
248                             CC->cs_pid, presence_jid);
249                 xmpp_destroy_buddy(presence_jid, 0);    /* non aggressive presence update */
250         }
251
252         free(cptr);
253 }
254
255
256
257 void xmpp_fetch_mortuary_backend(long msgnum, void *userdata) {
258         HashList *mortuary = (HashList *) userdata;
259         struct CtdlMessage *msg;
260         char *ptr = NULL;
261         char *lasts = NULL;
262
263         msg = CtdlFetchMessage(msgnum, 1);
264         if (msg == NULL) {
265                 return;
266         }
267
268         /* now add anyone we find into the hashlist */
269
270         /* skip past the headers */
271         ptr = strstr(msg->cm_fields[eMesageText], "\n\n");
272         if (ptr != NULL) {
273                 ptr += 2;
274         }
275         else {
276                 ptr = strstr(msg->cm_fields[eMesageText], "\n\r\n");
277                 if (ptr != NULL) {
278                         ptr += 3;
279                 }
280         }
281
282         /* the remaining lines are addresses */
283         if (ptr != NULL) {
284                 ptr = strtok_r(ptr, "\n", &lasts);
285                 while (ptr != NULL) {
286                         char *pch = strdup(ptr);
287                         Put(mortuary, pch, strlen(pch), pch, NULL);
288                         ptr = strtok_r(NULL, "\n", &lasts);
289                 }
290         }
291
292         CM_Free(msg);
293 }
294
295
296
297 /*
298  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
299  * so we can remove them from any client's roster that still has them listed
300  */
301 HashList *xmpp_fetch_mortuary(void) {
302         HashList *mortuary = NewHash(1, NULL);
303         if (!mortuary) {
304                 XMPPM_syslog(LOG_ALERT, "NewHash() failed!\n");
305                 return(NULL);
306         }
307
308         if (CtdlGetRoom(&CC->room, USERCONFIGROOM) != 0) {
309                 /* no config room exists - no further processing is required. */
310                 return(mortuary);
311         }
312         CtdlForEachMessage(MSGS_LAST, 1, NULL, XMPPMORTUARY, NULL,
313                 xmpp_fetch_mortuary_backend, (void *)mortuary );
314
315         return(mortuary);
316 }
317
318
319
320 /*
321  * Fetch the "mortuary" - a list of dead buddies which we keep around forever
322  * so we can remove them from any client's roster that still has them listed
323  */
324 void xmpp_store_mortuary(HashList *mortuary) {
325         HashPos *HashPos;
326         long len;
327         void *Value;
328         const char *Key;
329         StrBuf *themsg;
330
331         themsg = NewStrBuf();
332         StrBufPrintf(themsg,    "Content-type: " XMPPMORTUARY "\n"
333                                 "Content-transfer-encoding: 7bit\n"
334                                 "\n"
335         );
336
337         HashPos = GetNewHashPos(mortuary, 0);
338         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
339         {
340                 StrBufAppendPrintf(themsg, "%s\n", (char *)Value);
341         }
342         DeleteHashPos(&HashPos);
343
344         /* FIXME temp crap 
345         StrBufAppendPrintf(themsg, "foo@bar.com\n");
346         StrBufAppendPrintf(themsg, "baz@quux.com\n");
347         StrBufAppendPrintf(themsg, "haha%c\n", 1);
348         StrBufAppendPrintf(themsg, "baaaz@quux.com\n");
349         StrBufAppendPrintf(themsg, "baaaz@quuuuuux.com\n");
350         */
351
352         /* Delete the old mortuary */
353         CtdlDeleteMessages(USERCONFIGROOM, NULL, 0, XMPPMORTUARY);
354
355         /* And save the new one to disk */
356         quickie_message("Citadel", NULL, NULL, USERCONFIGROOM, ChrPtr(themsg), 4, "XMPP Mortuary");
357         FreeStrBuf(&themsg);
358 }
359
360
361
362 /*
363  * Upon logout we make an attempt to delete the whole roster, in order to
364  * try to keep "ghost" buddies from remaining in the client-side roster.
365  *
366  * Since the client is probably not still alive, also remember the current
367  * roster for next time so we can delete dead buddies then.
368  */
369 void xmpp_massacre_roster(void)
370 {
371         struct CitContext *cptr;
372         int nContexts, i;
373         HashList *mortuary = xmpp_fetch_mortuary();
374
375         cptr = CtdlGetContextArray(&nContexts);
376         if (cptr) {
377                 for (i=0; i<nContexts; i++) {
378                         if (xmpp_is_visible(&cptr[i], CC)) {
379                                 if (mortuary) {
380                                         char *buddy = strdup(cptr[i].cs_inet_email);
381                                         Put(mortuary, buddy, strlen(buddy), buddy, NULL);
382                                 }
383                         }
384                 }
385                 free (cptr);
386         }
387
388         if (mortuary) {
389                 xmpp_store_mortuary(mortuary);
390                 DeleteHash(&mortuary);
391         }
392 }
393
394
395
396 /*
397  * Stupidly, XMPP does not specify a way to tell the client to flush its client-side roster
398  * and prepare to receive a new one.  So instead we remember every buddy we've ever told the
399  * client about, and push delete operations out at the beginning of a session.
400  * 
401  * We omit any users who happen to be online right now, but we still keep them in the mortuary,
402  * which needs to be maintained as a list of every buddy the user has ever seen.  We don't know
403  * when they're connecting from the same client and when they're connecting from a different client,
404  * so we have no guarantee of what is in the client side roster at connect time.
405  */
406 void xmpp_delete_old_buddies_who_no_longer_exist_from_the_client_roster(void)
407 {
408         long len;
409         void *Value;
410         const char *Key;
411         struct CitContext *cptr;
412         int nContexts, i;
413         int online_now = 0;
414         HashList *mortuary = xmpp_fetch_mortuary();
415         HashPos *HashPos = GetNewHashPos(mortuary, 0);
416
417         /* we need to omit anyone who is currently online */
418         cptr = CtdlGetContextArray(&nContexts);
419
420         /* go through the list of users in the mortuary... */
421         while (GetNextHashPos(mortuary, HashPos, &len, &Key, &Value) != 0)
422         {
423
424                 online_now = 0;
425                 if (cptr) for (i=0; i<nContexts; i++) {
426                         if (xmpp_is_visible(&cptr[i], CC)) {
427                                 if (!strcasecmp(cptr[i].cs_inet_email, (char *)Value)) {
428                                         online_now = 1;
429                                 }
430                         }
431                 }
432
433                 if (!online_now) {
434                         xmpp_destroy_buddy((char *)Value, 1);   /* aggressive presence update */
435                 }
436
437         }
438         DeleteHashPos(&HashPos);
439         DeleteHash(&mortuary);
440         free(cptr);
441 }
442
443
444 CTDL_MODULE_INIT(xmpp_presence)
445 {
446         if (!threading) {
447                 AddXMPPEndHandler(HKEY("presence"), xmpp_wholist_presence_dump, 0);
448         }
449         return "xmpp_presence";
450 }