2c28600b665cc01d437439c6f5442499e46bfc20
[citadel.git] / citadel / modules / instmsg / serv_instmsg.c
1 /*
2  * This module handles instant messaging between users.
3  * 
4  * Copyright (c) 1987-2012 by the citadel.org team
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 version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14 #include "sysdep.h"
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <stdio.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #include <pwd.h>
21 #include <errno.h>
22 #include <sys/types.h>
23
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
26 # include <time.h>
27 #else
28 # if HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # else
31 #  include <time.h>
32 # endif
33 #endif
34
35 #include <sys/wait.h>
36 #include <string.h>
37 #include <limits.h>
38 #include <libcitadel.h>
39 #include "citadel.h"
40 #include "server.h"
41 #include "serv_instmsg.h"
42 #include "citserver.h"
43 #include "support.h"
44 #include "config.h"
45 #include "msgbase.h"
46 #include "user_ops.h"
47 #include "ctdl_module.h"
48
49 struct imlog {
50         struct imlog *next;
51         long usernums[2];
52         char usernames[2][128];
53         time_t lastmsg;
54         int last_serial;
55         StrBuf *conversation;
56 };
57
58 struct imlog *imlist = NULL;
59
60 /*
61  * This function handles the logging of instant messages to disk.
62  */
63 void log_instant_message(struct CitContext *me, struct CitContext *them, char *msgtext, int serial_number)
64 {
65         long usernums[2];
66         long t;
67         struct imlog *iptr = NULL;
68         struct imlog *this_im = NULL;
69         
70         memset(usernums, 0, sizeof usernums);
71         usernums[0] = me->user.usernum;
72         usernums[1] = them->user.usernum;
73
74         /* Always put the lower user number first, so we can use the array as a hash value which
75          * represents a pair of users.  For a broadcast message one of the users will be 0.
76          */
77         if (usernums[0] > usernums[1]) {
78                 t = usernums[0];
79                 usernums[0] = usernums[1];
80                 usernums[1] = t;
81         }
82
83         begin_critical_section(S_IM_LOGS);
84
85         /* Look for an existing conversation in the hash table.
86          * If not found, create a new one.
87          */
88
89         this_im = NULL;
90         for (iptr = imlist; iptr != NULL; iptr = iptr->next) {
91                 if ((iptr->usernums[0] == usernums[0]) && (iptr->usernums[1] == usernums[1])) {
92                         /* Existing conversation */
93                         this_im = iptr;
94                 }
95         }
96         if (this_im == NULL) {
97                 /* New conversation */
98                 this_im = malloc(sizeof(struct imlog));
99                 memset(this_im, 0, sizeof (struct imlog));
100                 this_im->usernums[0] = usernums[0];
101                 this_im->usernums[1] = usernums[1];
102                 /* usernames[] and usernums[] might not be in the same order.  This is not an error. */
103                 if (me) {
104                         safestrncpy(this_im->usernames[0], me->user.fullname, sizeof this_im->usernames[0]);
105                 }
106                 if (them) {
107                         safestrncpy(this_im->usernames[1], them->user.fullname, sizeof this_im->usernames[1]);
108                 }
109                 this_im->conversation = NewStrBuf();
110                 this_im->next = imlist;
111                 imlist = this_im;
112                 StrBufAppendBufPlain(this_im->conversation, HKEY(
113                         "<html><body>\r\n"
114                         ), 0);
115         }
116
117
118         /* Since it's possible for this function to get called more than once if a user is logged
119          * in on multiple sessions, we use the message's serial number to keep track of whether
120          * we've already logged it.
121          */
122         if (this_im->last_serial != serial_number)
123         {
124                 this_im->lastmsg = time(NULL);          /* Touch the timestamp so we know when to flush */
125                 this_im->last_serial = serial_number;
126                 StrBufAppendBufPlain(this_im->conversation, HKEY("<p><b>"), 0);
127                 StrBufAppendBufPlain(this_im->conversation, me->user.fullname, -1, 0);
128                 StrBufAppendBufPlain(this_im->conversation, HKEY(":</b> "), 0);
129                 StrEscAppend(this_im->conversation, NULL, msgtext, 0, 0);
130                 StrBufAppendBufPlain(this_im->conversation, HKEY("</p>\r\n"), 0);
131         }
132         end_critical_section(S_IM_LOGS);
133 }
134
135
136 /*
137  * Delete any remaining instant messages
138  */
139 void delete_instant_messages(void) {
140         struct ExpressMessage *ptr;
141
142         begin_critical_section(S_SESSION_TABLE);
143         while (CC->FirstExpressMessage != NULL) {
144                 ptr = CC->FirstExpressMessage->next;
145                 if (CC->FirstExpressMessage->text != NULL)
146                         free(CC->FirstExpressMessage->text);
147                 free(CC->FirstExpressMessage);
148                 CC->FirstExpressMessage = ptr;
149         }
150         end_critical_section(S_SESSION_TABLE);
151 }
152
153
154
155 /*
156  * Retrieve instant messages
157  */
158 void cmd_gexp(char *argbuf) {
159         struct ExpressMessage *ptr;
160
161         if (CC->FirstExpressMessage == NULL) {
162                 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
163                 return;
164         }
165
166         begin_critical_section(S_SESSION_TABLE);
167         ptr = CC->FirstExpressMessage;
168         CC->FirstExpressMessage = CC->FirstExpressMessage->next;
169         end_critical_section(S_SESSION_TABLE);
170
171         cprintf("%d %d|%ld|%d|%s|%s|%s\n",
172                 LISTING_FOLLOWS,
173                 ((ptr->next != NULL) ? 1 : 0),          /* more msgs? */
174                 (long)ptr->timestamp,                   /* time sent */
175                 ptr->flags,                             /* flags */
176                 ptr->sender,                            /* sender of msg */
177                 config.c_nodename,                      /* static for now (and possibly deprecated) */
178                 ptr->sender_email                       /* email or jid of sender */
179         );
180
181         if (ptr->text != NULL) {
182                 memfmout(ptr->text, "\n");
183                 free(ptr->text);
184         }
185
186         cprintf("000\n");
187         free(ptr);
188 }
189
190 /*
191  * Asynchronously deliver instant messages
192  */
193 void cmd_gexp_async(void) {
194
195         /* Only do this if the session can handle asynchronous protocol */
196         if (CC->is_async == 0) return;
197
198         /* And don't do it if there's nothing to send. */
199         if (CC->FirstExpressMessage == NULL) return;
200
201         cprintf("%d instant msg\n", ASYNC_MSG + ASYNC_GEXP);
202 }
203
204 /*
205  * Back end support function for send_instant_message() and company
206  */
207 void add_xmsg_to_context(struct CitContext *ccptr, struct ExpressMessage *newmsg) 
208 {
209         struct ExpressMessage *findend;
210
211         if (ccptr->FirstExpressMessage == NULL) {
212                 ccptr->FirstExpressMessage = newmsg;
213         }
214         else {
215                 findend = ccptr->FirstExpressMessage;
216                 while (findend->next != NULL) {
217                         findend = findend->next;
218                 }
219                 findend->next = newmsg;
220         }
221
222         /* If the target context is a session which can handle asynchronous
223          * messages, go ahead and set the flag for that.
224          */
225         set_async_waiting(ccptr);
226 }
227
228
229
230
231 /* 
232  * This is the back end to the instant message sending function.  
233  * Returns the number of users to which the message was sent.
234  * Sending a zero-length message tests for recipients without sending messages.
235  */
236 int send_instant_message(char *lun, char *lem, char *x_user, char *x_msg)
237 {
238         int message_sent = 0;           /* number of successful sends */
239         struct CitContext *ccptr;
240         struct ExpressMessage *newmsg = NULL;
241         char *un;
242         int do_send = 0;                /* 1 = send message; 0 = only check for valid recipient */
243         static int serial_number = 0;   /* this keeps messages from getting logged twice */
244
245         if (strlen(x_msg) > 0) {
246                 do_send = 1;
247         }
248
249         /* find the target user's context and append the message */
250         begin_critical_section(S_SESSION_TABLE);
251         ++serial_number;
252         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
253
254                 if (ccptr->fake_username[0]) {
255                         un = ccptr->fake_username;
256                 }
257                 else {
258                         un = ccptr->user.fullname;
259                 }
260
261                 if ( ((!strcasecmp(un, x_user))
262                     || (!strcasecmp(x_user, "broadcast")))
263                     && (ccptr->can_receive_im)
264                     && ((ccptr->disable_exp == 0)
265                     || (CC->user.axlevel >= AxAideU)) ) {
266                         if (do_send) {
267                                 newmsg = (struct ExpressMessage *) malloc(sizeof (struct ExpressMessage));
268                                 memset(newmsg, 0, sizeof (struct ExpressMessage));
269                                 time(&(newmsg->timestamp));
270                                 safestrncpy(newmsg->sender, lun, sizeof newmsg->sender);
271                                 safestrncpy(newmsg->sender_email, lem, sizeof newmsg->sender_email);
272                                 if (!strcasecmp(x_user, "broadcast")) {
273                                         newmsg->flags |= EM_BROADCAST;
274                                 }
275                                 newmsg->text = strdup(x_msg);
276
277                                 add_xmsg_to_context(ccptr, newmsg);
278
279                                 /* and log it ... */
280                                 if (ccptr != CC) {
281                                         log_instant_message(CC, ccptr, newmsg->text, serial_number);
282                                 }
283                         }
284                         ++message_sent;
285                 }
286         }
287         end_critical_section(S_SESSION_TABLE);
288         return (message_sent);
289 }
290
291 /*
292  * send instant messages
293  */
294 void cmd_sexp(char *argbuf)
295 {
296         int message_sent = 0;
297         char x_user[USERNAME_SIZE];
298         char x_msg[1024];
299         char *lun;
300         char *lem;
301         char *x_big_msgbuf = NULL;
302
303         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
304                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
305                 return;
306         }
307         if (CC->fake_username[0])
308                 lun = CC->fake_username;
309         else
310                 lun = CC->user.fullname;
311
312         lem = CC->cs_inet_email;
313
314         extract_token(x_user, argbuf, 0, '|', sizeof x_user);
315         extract_token(x_msg, argbuf, 1, '|', sizeof x_msg);
316
317         if (!x_user[0]) {
318                 cprintf("%d You were not previously paged.\n", ERROR + NO_SUCH_USER);
319                 return;
320         }
321         if ((!strcasecmp(x_user, "broadcast")) && (CC->user.axlevel < AxAideU)) {
322                 cprintf("%d Higher access required to send a broadcast.\n",
323                         ERROR + HIGHER_ACCESS_REQUIRED);
324                 return;
325         }
326         /* This loop handles text-transfer pages */
327         if (!strcmp(x_msg, "-")) {
328                 message_sent = PerformXmsgHooks(lun, lem, x_user, "");
329                 if (message_sent == 0) {
330                         if (CtdlGetUser(NULL, x_user))
331                                 cprintf("%d '%s' does not exist.\n",
332                                                 ERROR + NO_SUCH_USER, x_user);
333                         else
334                                 cprintf("%d '%s' is not logged in "
335                                                 "or is not accepting pages.\n",
336                                                 ERROR + RESOURCE_NOT_OPEN, x_user);
337                         return;
338                 }
339                 unbuffer_output();
340                 cprintf("%d Transmit message (will deliver to %d users)\n",
341                         SEND_LISTING, message_sent);
342                 x_big_msgbuf = malloc(SIZ);
343                 memset(x_big_msgbuf, 0, SIZ);
344                 while (client_getln(x_msg, sizeof x_msg) >= 0 && strcmp(x_msg, "000")) {
345                         x_big_msgbuf = realloc(x_big_msgbuf,
346                                strlen(x_big_msgbuf) + strlen(x_msg) + 4);
347                         if (!IsEmptyStr(x_big_msgbuf))
348                            if (x_big_msgbuf[strlen(x_big_msgbuf)] != '\n')
349                                 strcat(x_big_msgbuf, "\n");
350                         strcat(x_big_msgbuf, x_msg);
351                 }
352                 PerformXmsgHooks(lun, lem, x_user, x_big_msgbuf);
353                 free(x_big_msgbuf);
354
355                 /* This loop handles inline pages */
356         } else {
357                 message_sent = PerformXmsgHooks(lun, lem, x_user, x_msg);
358
359                 if (message_sent > 0) {
360                         if (!IsEmptyStr(x_msg))
361                                 cprintf("%d Message sent", CIT_OK);
362                         else
363                                 cprintf("%d Ok to send message", CIT_OK);
364                         if (message_sent > 1)
365                                 cprintf(" to %d users", message_sent);
366                         cprintf(".\n");
367                 } else {
368                         if (CtdlGetUser(NULL, x_user))
369                                 cprintf("%d '%s' does not exist.\n",
370                                                 ERROR + NO_SUCH_USER, x_user);
371                         else
372                                 cprintf("%d '%s' is not logged in "
373                                                 "or is not accepting pages.\n",
374                                                 ERROR + RESOURCE_NOT_OPEN, x_user);
375                 }
376
377
378         }
379 }
380
381
382
383 /*
384  * Enter or exit paging-disabled mode
385  */
386 void cmd_dexp(char *argbuf)
387 {
388         int new_state;
389
390         if (CtdlAccessCheck(ac_logged_in)) return;
391
392         new_state = extract_int(argbuf, 0);
393         if ((new_state == 0) || (new_state == 1)) {
394                 CC->disable_exp = new_state;
395         }
396
397         cprintf("%d %d\n", CIT_OK, CC->disable_exp);
398 }
399
400
401 /*
402  * Request client termination
403  */
404 void cmd_reqt(char *argbuf) {
405         struct CitContext *ccptr;
406         int sessions = 0;
407         int which_session;
408         struct ExpressMessage *newmsg;
409
410         if (CtdlAccessCheck(ac_aide)) return;
411         which_session = extract_int(argbuf, 0);
412
413         begin_critical_section(S_SESSION_TABLE);
414         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
415                 if ((ccptr->cs_pid == which_session) || (which_session == 0)) {
416
417                         newmsg = (struct ExpressMessage *)
418                                 malloc(sizeof (struct ExpressMessage));
419                         memset(newmsg, 0,
420                                 sizeof (struct ExpressMessage));
421                         time(&(newmsg->timestamp));
422                         safestrncpy(newmsg->sender, CC->user.fullname,
423                                     sizeof newmsg->sender);
424                         newmsg->flags |= EM_GO_AWAY;
425                         newmsg->text = strdup("Automatic logoff requested.");
426
427                         add_xmsg_to_context(ccptr, newmsg);
428                         ++sessions;
429
430                 }
431         }
432         end_critical_section(S_SESSION_TABLE);
433         cprintf("%d Sent termination request to %d sessions.\n", CIT_OK, sessions);
434 }
435
436
437 /*
438  * This is the back end for flush_conversations_to_disk()
439  * At this point we've isolated a single conversation (struct imlog)
440  * and are ready to write it to disk.
441  */
442 void flush_individual_conversation(struct imlog *im) {
443         struct CtdlMessage *msg;
444         long msgnum = 0;
445         char roomname[ROOMNAMELEN];
446         StrBuf *MsgBuf, *FullMsgBuf;
447
448         StrBufAppendBufPlain(im->conversation, HKEY(
449                 "</body>\r\n"
450                 "</html>\r\n"
451                 ), 0
452         );
453
454         MsgBuf = StrBufRFC2047encodeMessage(im->conversation);
455         FlushStrBuf(im->conversation);
456         FullMsgBuf = NewStrBufPlain(NULL, StrLength(im->conversation) + 100);
457
458         StrBufAppendBufPlain(FullMsgBuf, HKEY(
459                         "Content-type: text/html; charset=UTF-8\r\n"
460                         "Content-Transfer-Encoding: quoted-printable\r\n"
461                         "\r\n"
462                         ), 0);
463         StrBufAppendBuf (FullMsgBuf, MsgBuf, 0);
464         FreeStrBuf(&MsgBuf);
465
466         msg = malloc(sizeof(struct CtdlMessage));
467         memset(msg, 0, sizeof(struct CtdlMessage));
468         msg->cm_magic = CTDLMESSAGE_MAGIC;
469         msg->cm_anon_type = MES_NORMAL;
470         msg->cm_format_type = FMT_RFC822;
471         if (!IsEmptyStr(im->usernames[0])) {
472                 CM_SetField(msg, eAuthor, im->usernames[0], strlen(im->usernames[0]));
473         } else {
474                 CM_SetField(msg, eAuthor, HKEY("Citadel"));
475         }
476         if (!IsEmptyStr(im->usernames[1])) {
477                 CM_SetField(msg, eRecipient, im->usernames[1], strlen(im->usernames[1]));
478         }
479
480         CM_SetField(msg, eOriginalRoom, HKEY(PAGELOGROOM));
481         CM_SetField(msg, eNodeName, CFG_KEY(c_nodename));
482         CM_SetAsFieldSB(msg, eMesageText, &FullMsgBuf); /* we own this memory now */
483
484         /* Start with usernums[1] because it's guaranteed to be higher than usernums[0],
485          * so if there's only one party, usernums[0] will be zero but usernums[1] won't.
486          * Create the room if necessary.  Note that we create as a type 5 room rather
487          * than 4, which indicates that it's a personal room but we've already supplied
488          * the namespace prefix.
489          *
490          * In the unlikely event that usernums[1] is zero, a room with an invalid namespace
491          * prefix will be created.  That's ok because the auto-purger will clean it up later.
492          */
493         snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[1], PAGELOGROOM);
494         CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
495         msgnum = CtdlSubmitMsg(msg, NULL, roomname, 0);
496         CM_Free(msg);
497
498         /* If there is a valid user number in usernums[0], save a copy for them too. */
499         if (im->usernums[0] > 0) {
500                 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[0], PAGELOGROOM);
501                 CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
502                 CtdlSaveMsgPointerInRoom(roomname, msgnum, 0, NULL);
503         }
504
505         /* Finally, if we're logging instant messages globally, do that now. */
506         if (!IsEmptyStr(config.c_logpages)) {
507                 CtdlCreateRoom(config.c_logpages, 3, "", 0, 1, 1, VIEW_BBS);
508                 CtdlSaveMsgPointerInRoom(config.c_logpages, msgnum, 0, NULL);
509         }
510
511 }
512
513 /*
514  * Locate instant message conversations which have gone idle
515  * (or, if the server is shutting down, locate *all* conversations)
516  * and flush them to disk (in the participants' log rooms, etc.)
517  */
518 void flush_conversations_to_disk(time_t if_older_than) {
519
520         struct imlog *flush_these = NULL;
521         struct imlog *dont_flush_these = NULL;
522         struct imlog *imptr = NULL;
523         struct CitContext *nptr;
524         int nContexts, i;
525
526         nptr = CtdlGetContextArray(&nContexts) ;        /* Make a copy of the current wholist */
527
528         begin_critical_section(S_IM_LOGS);
529         while (imlist)
530         {
531                 imptr = imlist;
532                 imlist = imlist->next;
533
534                 /* For a two party conversation, if one party has logged out, force flush. */
535                 if (nptr) {
536                         int user0_is_still_online = 0;
537                         int user1_is_still_online = 0;
538                         for (i=0; i<nContexts; i++)  {
539                                 if (nptr[i].user.usernum == imptr->usernums[0]) ++user0_is_still_online;
540                                 if (nptr[i].user.usernum == imptr->usernums[1]) ++user1_is_still_online;
541                         }
542                         if (imptr->usernums[0] != imptr->usernums[1]) {         /* two party conversation */
543                                 if ((!user0_is_still_online) || (!user1_is_still_online)) {
544                                         imptr->lastmsg = 0L;    /* force flush */
545                                 }
546                         }
547                         else {          /* one party conversation (yes, people do IM themselves) */
548                                 if (!user0_is_still_online) {
549                                         imptr->lastmsg = 0L;    /* force flush */
550                                 }
551                         }
552                 }
553
554                 /* Now test this conversation to see if it qualifies for flushing. */
555                 if ((time(NULL) - imptr->lastmsg) > if_older_than)
556                 {
557                         /* This conversation qualifies.  Move it to the list of ones to flush. */
558                         imptr->next = flush_these;
559                         flush_these = imptr;
560                 }
561                 else  {
562                         /* Move it to the list of ones not to flush. */
563                         imptr->next = dont_flush_these;
564                         dont_flush_these = imptr;
565                 }
566         }
567         imlist = dont_flush_these;
568         end_critical_section(S_IM_LOGS);
569         free(nptr);
570
571         /* We are now outside of the critical section, and we are the only thread holding a
572          * pointer to a linked list of conversations to be flushed to disk.
573          */
574         while (flush_these) {
575
576                 flush_individual_conversation(flush_these);     /* This will free the string buffer */
577                 imptr = flush_these;
578                 flush_these = flush_these->next;
579                 free(imptr);
580         }
581 }
582
583
584
585 void instmsg_timer(void) {
586         flush_conversations_to_disk(300);       /* Anything that hasn't peeped in more than 5 minutes */
587 }
588
589 void instmsg_shutdown(void) {
590         flush_conversations_to_disk(0);         /* Get it ALL onto disk NOW. */
591 }
592
593 CTDL_MODULE_INIT(instmsg)
594 {
595         if (!threading)
596         {
597                 CtdlRegisterProtoHook(cmd_gexp, "GEXP", "Get instant messages");
598                 CtdlRegisterProtoHook(cmd_sexp, "SEXP", "Send an instant message");
599                 CtdlRegisterProtoHook(cmd_dexp, "DEXP", "Disable instant messages");
600                 CtdlRegisterProtoHook(cmd_reqt, "REQT", "Request client termination");
601                 CtdlRegisterSessionHook(cmd_gexp_async, EVT_ASYNC, PRIO_ASYNC + 1);
602                 CtdlRegisterSessionHook(delete_instant_messages, EVT_STOP, PRIO_STOP + 1);
603                 CtdlRegisterXmsgHook(send_instant_message, XMSG_PRI_LOCAL);
604                 CtdlRegisterSessionHook(instmsg_timer, EVT_TIMER, PRIO_CLEANUP + 400);
605                 CtdlRegisterSessionHook(instmsg_shutdown, EVT_SHUTDOWN, PRIO_SHUTDOWN + 10);
606         }
607         
608         /* return our module name for the log */
609         return "instmsg";
610 }