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