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