2 * This module handles instant messaging between users.
4 * Copyright (c) 1987-2018 by the citadel.org team
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.
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.
23 #include <sys/types.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
39 #include <libcitadel.h>
42 #include "serv_instmsg.h"
43 #include "citserver.h"
48 #include "ctdl_module.h"
53 char usernames[2][128];
59 struct imlog *imlist = NULL;
62 * This function handles the logging of instant messages to disk.
64 void log_instant_message(struct CitContext *me, struct CitContext *them, char *msgtext, int serial_number)
68 struct imlog *iptr = NULL;
69 struct imlog *this_im = NULL;
71 memset(usernums, 0, sizeof usernums);
72 usernums[0] = me->user.usernum;
73 usernums[1] = them->user.usernum;
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.
78 if (usernums[0] > usernums[1]) {
80 usernums[0] = usernums[1];
84 begin_critical_section(S_IM_LOGS);
86 /* Look for an existing conversation in the hash table.
87 * If not found, create a new one.
91 for (iptr = imlist; iptr != NULL; iptr = iptr->next) {
92 if ((iptr->usernums[0] == usernums[0]) && (iptr->usernums[1] == usernums[1])) {
93 /* Existing conversation */
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. */
105 safestrncpy(this_im->usernames[0], me->user.fullname, sizeof this_im->usernames[0]);
108 safestrncpy(this_im->usernames[1], them->user.fullname, sizeof this_im->usernames[1]);
110 this_im->conversation = NewStrBuf();
111 this_im->next = imlist;
113 StrBufAppendBufPlain(this_im->conversation, HKEY("<html><body>\r\n"), 0);
116 /* Since it's possible for this function to get called more than once if a user is logged
117 * in on multiple sessions, we use the message's serial number to keep track of whether
118 * we've already logged it.
120 if (this_im->last_serial != serial_number)
122 this_im->lastmsg = time(NULL); /* Touch the timestamp so we know when to flush */
123 this_im->last_serial = serial_number;
124 StrBufAppendBufPlain(this_im->conversation, HKEY("<p><b>"), 0);
125 StrBufAppendBufPlain(this_im->conversation, me->user.fullname, -1, 0);
126 StrBufAppendBufPlain(this_im->conversation, HKEY(":</b> "), 0);
127 StrEscAppend(this_im->conversation, NULL, msgtext, 0, 0);
128 StrBufAppendBufPlain(this_im->conversation, HKEY("</p>\r\n"), 0);
130 end_critical_section(S_IM_LOGS);
135 * Delete any remaining instant messages
137 void delete_instant_messages(void) {
138 struct ExpressMessage *ptr;
140 begin_critical_section(S_SESSION_TABLE);
141 while (CC->FirstExpressMessage != NULL) {
142 ptr = CC->FirstExpressMessage->next;
143 if (CC->FirstExpressMessage->text != NULL)
144 free(CC->FirstExpressMessage->text);
145 free(CC->FirstExpressMessage);
146 CC->FirstExpressMessage = ptr;
148 end_critical_section(S_SESSION_TABLE);
153 * Retrieve instant messages
155 void cmd_gexp(char *argbuf) {
156 struct ExpressMessage *ptr;
158 if (CC->FirstExpressMessage == NULL) {
159 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
163 begin_critical_section(S_SESSION_TABLE);
164 ptr = CC->FirstExpressMessage;
165 CC->FirstExpressMessage = CC->FirstExpressMessage->next;
166 end_critical_section(S_SESSION_TABLE);
168 cprintf("%d %d|%ld|%d|%s|%s|%s\n",
170 ((ptr->next != NULL) ? 1 : 0), /* more msgs? */
171 (long)ptr->timestamp, /* time sent */
172 ptr->flags, /* flags */
173 ptr->sender, /* sender of msg */
174 CtdlGetConfigStr("c_nodename"), /* static for now (and possibly deprecated) */
175 ptr->sender_email /* email or jid of sender */
178 if (ptr->text != NULL) {
179 memfmout(ptr->text, "\n");
189 * Asynchronously deliver instant messages
191 void cmd_gexp_async(void) {
193 /* Only do this if the session can handle asynchronous protocol */
194 if (CC->is_async == 0) return;
196 /* And don't do it if there's nothing to send. */
197 if (CC->FirstExpressMessage == NULL) return;
199 cprintf("%d instant msg\n", ASYNC_MSG + ASYNC_GEXP);
204 * Back end support function for send_instant_message() and company
206 void add_xmsg_to_context(struct CitContext *ccptr, struct ExpressMessage *newmsg)
208 struct ExpressMessage *findend;
210 if (ccptr->FirstExpressMessage == NULL) {
211 ccptr->FirstExpressMessage = newmsg;
214 findend = ccptr->FirstExpressMessage;
215 while (findend->next != NULL) {
216 findend = findend->next;
218 findend->next = newmsg;
221 /* If the target context is a session which can handle asynchronous
222 * messages, go ahead and set the flag for that.
224 set_async_waiting(ccptr);
229 * This is the back end to the instant message sending function.
230 * Returns the number of users to which the message was sent.
231 * Sending a zero-length message tests for recipients without sending messages.
233 int send_instant_message(char *lun, char *lem, char *x_user, char *x_msg)
235 int message_sent = 0; /* number of successful sends */
236 struct CitContext *ccptr;
237 struct ExpressMessage *newmsg = NULL;
239 int do_send = 0; /* 1 = send message; 0 = only check for valid recipient */
240 static int serial_number = 0; /* this keeps messages from getting logged twice */
242 if (!IsEmptyStr(x_msg)) {
246 /* find the target user's context and append the message */
247 begin_critical_section(S_SESSION_TABLE);
249 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
251 if (ccptr->fake_username[0]) {
252 un = ccptr->fake_username;
255 un = ccptr->user.fullname;
258 if ( ((!strcasecmp(un, x_user))
259 || (!strcasecmp(x_user, "broadcast")))
260 && (ccptr->can_receive_im)
261 && ((ccptr->disable_exp == 0)
262 || (CC->user.axlevel >= AxAideU)) ) {
264 newmsg = (struct ExpressMessage *) malloc(sizeof (struct ExpressMessage));
265 memset(newmsg, 0, sizeof (struct ExpressMessage));
266 time(&(newmsg->timestamp));
267 safestrncpy(newmsg->sender, lun, sizeof newmsg->sender);
268 safestrncpy(newmsg->sender_email, lem, sizeof newmsg->sender_email);
269 if (!strcasecmp(x_user, "broadcast")) {
270 newmsg->flags |= EM_BROADCAST;
272 newmsg->text = strdup(x_msg);
274 add_xmsg_to_context(ccptr, newmsg);
278 log_instant_message(CC, ccptr, newmsg->text, serial_number);
284 end_critical_section(S_SESSION_TABLE);
285 return (message_sent);
290 * send instant messages
292 void cmd_sexp(char *argbuf)
294 int message_sent = 0;
295 char x_user[USERNAME_SIZE];
299 char *x_big_msgbuf = NULL;
301 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
302 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
305 if (CC->fake_username[0]) {
306 lun = CC->fake_username;
309 lun = CC->user.fullname;
312 lem = CC->cs_inet_email;
314 extract_token(x_user, argbuf, 0, '|', sizeof x_user);
315 extract_token(x_msg, argbuf, 1, '|', sizeof x_msg);
318 cprintf("%d You were not previously paged.\n", ERROR + NO_SUCH_USER);
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);
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);
334 cprintf("%d '%s' is not logged in "
335 "or is not accepting pages.\n",
336 ERROR + RESOURCE_NOT_OPEN, x_user);
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);
352 PerformXmsgHooks(lun, lem, x_user, x_big_msgbuf);
355 /* This loop handles inline pages */
357 message_sent = PerformXmsgHooks(lun, lem, x_user, x_msg);
359 if (message_sent > 0) {
360 if (!IsEmptyStr(x_msg)) {
361 cprintf("%d Message sent", CIT_OK);
364 cprintf("%d Ok to send message", CIT_OK);
366 if (message_sent > 1) {
367 cprintf(" to %d users", message_sent);
371 if (CtdlGetUser(NULL, x_user)) {
372 cprintf("%d '%s' does not exist.\n", ERROR + NO_SUCH_USER, x_user);
375 cprintf("%d '%s' is not logged in or is not accepting instant messages.\n",
376 ERROR + RESOURCE_NOT_OPEN, x_user);
386 * Enter or exit paging-disabled mode
388 void cmd_dexp(char *argbuf)
392 if (CtdlAccessCheck(ac_logged_in)) return;
394 new_state = extract_int(argbuf, 0);
395 if ((new_state == 0) || (new_state == 1)) {
396 CC->disable_exp = new_state;
399 cprintf("%d %d\n", CIT_OK, CC->disable_exp);
404 * Request client termination
406 void cmd_reqt(char *argbuf) {
407 struct CitContext *ccptr;
410 struct ExpressMessage *newmsg;
412 if (CtdlAccessCheck(ac_aide)) return;
413 which_session = extract_int(argbuf, 0);
415 begin_critical_section(S_SESSION_TABLE);
416 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
417 if ((ccptr->cs_pid == which_session) || (which_session == 0)) {
419 newmsg = (struct ExpressMessage *)
420 malloc(sizeof (struct ExpressMessage));
422 sizeof (struct ExpressMessage));
423 time(&(newmsg->timestamp));
424 safestrncpy(newmsg->sender, CC->user.fullname,
425 sizeof newmsg->sender);
426 newmsg->flags |= EM_GO_AWAY;
427 newmsg->text = strdup("Automatic logoff requested.");
429 add_xmsg_to_context(ccptr, newmsg);
434 end_critical_section(S_SESSION_TABLE);
435 cprintf("%d Sent termination request to %d sessions.\n", CIT_OK, sessions);
440 * This is the back end for flush_conversations_to_disk()
441 * At this point we've isolated a single conversation (struct imlog)
442 * and are ready to write it to disk.
444 void flush_individual_conversation(struct imlog *im) {
445 struct CtdlMessage *msg;
447 char roomname[ROOMNAMELEN];
448 StrBuf *MsgBuf, *FullMsgBuf;
450 StrBufAppendBufPlain(im->conversation, HKEY(
456 MsgBuf = StrBufRFC2047encodeMessage(im->conversation);
457 FlushStrBuf(im->conversation);
458 FullMsgBuf = NewStrBufPlain(NULL, StrLength(im->conversation) + 100);
460 StrBufAppendBufPlain(FullMsgBuf, HKEY(
461 "Content-type: text/html; charset=UTF-8\r\n"
462 "Content-Transfer-Encoding: quoted-printable\r\n"
466 StrBufAppendBuf (FullMsgBuf, MsgBuf, 0);
469 msg = malloc(sizeof(struct CtdlMessage));
470 memset(msg, 0, sizeof(struct CtdlMessage));
471 msg->cm_magic = CTDLMESSAGE_MAGIC;
472 msg->cm_anon_type = MES_NORMAL;
473 msg->cm_format_type = FMT_RFC822;
474 if (!IsEmptyStr(im->usernames[0])) {
475 CM_SetField(msg, eAuthor, im->usernames[0], strlen(im->usernames[0]));
477 CM_SetField(msg, eAuthor, HKEY("Citadel"));
479 if (!IsEmptyStr(im->usernames[1])) {
480 CM_SetField(msg, eRecipient, im->usernames[1], strlen(im->usernames[1]));
483 CM_SetField(msg, eOriginalRoom, HKEY(PAGELOGROOM));
484 CM_SetAsFieldSB(msg, eMesageText, &FullMsgBuf); /* we own this memory now */
486 /* Start with usernums[1] because it's guaranteed to be higher than usernums[0],
487 * so if there's only one party, usernums[0] will be zero but usernums[1] won't.
488 * Create the room if necessary. Note that we create as a type 5 room rather
489 * than 4, which indicates that it's a personal room but we've already supplied
490 * the namespace prefix.
492 * In the unlikely event that usernums[1] is zero, a room with an invalid namespace
493 * prefix will be created. That's ok because the auto-purger will clean it up later.
495 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[1], PAGELOGROOM);
496 CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
497 msgnum = CtdlSubmitMsg(msg, NULL, roomname, 0);
500 /* If there is a valid user number in usernums[0], save a copy for them too. */
501 if (im->usernums[0] > 0) {
502 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[0], PAGELOGROOM);
503 CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
504 CtdlSaveMsgPointerInRoom(roomname, msgnum, 0, NULL);
507 /* Finally, if we're logging instant messages globally, do that now. */
508 if (!IsEmptyStr(CtdlGetConfigStr("c_logpages"))) {
509 CtdlCreateRoom(CtdlGetConfigStr("c_logpages"), 3, "", 0, 1, 1, VIEW_BBS);
510 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_logpages"), msgnum, 0, NULL);
516 * Locate instant message conversations which have gone idle
517 * (or, if the server is shutting down, locate *all* conversations)
518 * and flush them to disk (in the participants' log rooms, etc.)
520 void flush_conversations_to_disk(time_t if_older_than) {
522 struct imlog *flush_these = NULL;
523 struct imlog *dont_flush_these = NULL;
524 struct imlog *imptr = NULL;
525 struct CitContext *nptr;
528 nptr = CtdlGetContextArray(&nContexts) ; /* Make a copy of the current wholist */
530 begin_critical_section(S_IM_LOGS);
534 imlist = imlist->next;
536 /* For a two party conversation, if one party has logged out, force flush. */
538 int user0_is_still_online = 0;
539 int user1_is_still_online = 0;
540 for (i=0; i<nContexts; i++) {
541 if (nptr[i].user.usernum == imptr->usernums[0]) ++user0_is_still_online;
542 if (nptr[i].user.usernum == imptr->usernums[1]) ++user1_is_still_online;
544 if (imptr->usernums[0] != imptr->usernums[1]) { /* two party conversation */
545 if ((!user0_is_still_online) || (!user1_is_still_online)) {
546 imptr->lastmsg = 0L; /* force flush */
549 else { /* one party conversation (yes, people do IM themselves) */
550 if (!user0_is_still_online) {
551 imptr->lastmsg = 0L; /* force flush */
556 /* Now test this conversation to see if it qualifies for flushing. */
557 if ((time(NULL) - imptr->lastmsg) > if_older_than)
559 /* This conversation qualifies. Move it to the list of ones to flush. */
560 imptr->next = flush_these;
564 /* Move it to the list of ones not to flush. */
565 imptr->next = dont_flush_these;
566 dont_flush_these = imptr;
569 imlist = dont_flush_these;
570 end_critical_section(S_IM_LOGS);
573 /* We are now outside of the critical section, and we are the only thread holding a
574 * pointer to a linked list of conversations to be flushed to disk.
576 while (flush_these) {
578 flush_individual_conversation(flush_these); /* This will free the string buffer */
580 flush_these = flush_these->next;
587 void instmsg_timer(void) {
588 flush_conversations_to_disk(300); /* Anything that hasn't peeped in more than 5 minutes */
591 void instmsg_shutdown(void) {
592 flush_conversations_to_disk(0); /* Get it ALL onto disk NOW. */
595 CTDL_MODULE_INIT(instmsg)
599 CtdlRegisterProtoHook(cmd_gexp, "GEXP", "Get instant messages");
600 CtdlRegisterProtoHook(cmd_sexp, "SEXP", "Send an instant message");
601 CtdlRegisterProtoHook(cmd_dexp, "DEXP", "Disable instant messages");
602 CtdlRegisterProtoHook(cmd_reqt, "REQT", "Request client termination");
603 CtdlRegisterSessionHook(cmd_gexp_async, EVT_ASYNC, PRIO_ASYNC + 1);
604 CtdlRegisterSessionHook(delete_instant_messages, EVT_STOP, PRIO_STOP + 1);
605 CtdlRegisterXmsgHook(send_instant_message, XMSG_PRI_LOCAL);
606 CtdlRegisterSessionHook(instmsg_timer, EVT_TIMER, PRIO_CLEANUP + 400);
607 CtdlRegisterSessionHook(instmsg_shutdown, EVT_SHUTDOWN, PRIO_SHUTDOWN + 10);
610 /* return our module name for the log */