2 * This module handles instant messaging between users.
4 * Copyright (c) 1987-2012 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.
22 #include <sys/types.h>
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
29 # include <sys/time.h>
38 #include <libcitadel.h>
41 #include "serv_instmsg.h"
42 #include "citserver.h"
47 #include "ctdl_module.h"
52 char usernames[2][128];
58 struct imlog *imlist = NULL;
61 * This function handles the logging of instant messages to disk.
63 void log_instant_message(struct CitContext *me, struct CitContext *them, char *msgtext, int serial_number)
67 struct imlog *iptr = NULL;
68 struct imlog *this_im = NULL;
70 memset(usernums, 0, sizeof usernums);
71 usernums[0] = me->user.usernum;
72 usernums[1] = them->user.usernum;
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.
77 if (usernums[0] > usernums[1]) {
79 usernums[0] = usernums[1];
83 begin_critical_section(S_IM_LOGS);
85 /* Look for an existing conversation in the hash table.
86 * If not found, create a new one.
90 for (iptr = imlist; iptr != NULL; iptr = iptr->next) {
91 if ((iptr->usernums[0] == usernums[0]) && (iptr->usernums[1] == usernums[1])) {
92 /* Existing conversation */
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. */
104 safestrncpy(this_im->usernames[0], me->user.fullname, sizeof this_im->usernames[0]);
107 safestrncpy(this_im->usernames[1], them->user.fullname, sizeof this_im->usernames[1]);
109 this_im->conversation = NewStrBuf();
110 this_im->next = imlist;
112 StrBufAppendBufPlain(this_im->conversation, HKEY(
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.
122 if (this_im->last_serial != serial_number)
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);
132 end_critical_section(S_IM_LOGS);
137 * Delete any remaining instant messages
139 void delete_instant_messages(void) {
140 struct ExpressMessage *ptr;
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;
150 end_critical_section(S_SESSION_TABLE);
156 * Retrieve instant messages
158 void cmd_gexp(char *argbuf) {
159 struct ExpressMessage *ptr;
161 if (CC->FirstExpressMessage == NULL) {
162 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
166 begin_critical_section(S_SESSION_TABLE);
167 ptr = CC->FirstExpressMessage;
168 CC->FirstExpressMessage = CC->FirstExpressMessage->next;
169 end_critical_section(S_SESSION_TABLE);
171 cprintf("%d %d|%ld|%d|%s|%s|%s\n",
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 */
181 if (ptr->text != NULL) {
182 memfmout(ptr->text, "\n");
191 * Asynchronously deliver instant messages
193 void cmd_gexp_async(void) {
195 /* Only do this if the session can handle asynchronous protocol */
196 if (CC->is_async == 0) return;
198 /* And don't do it if there's nothing to send. */
199 if (CC->FirstExpressMessage == NULL) return;
201 cprintf("%d instant msg\n", ASYNC_MSG + ASYNC_GEXP);
205 * Back end support function for send_instant_message() and company
207 void add_xmsg_to_context(struct CitContext *ccptr, struct ExpressMessage *newmsg)
209 struct ExpressMessage *findend;
211 if (ccptr->FirstExpressMessage == NULL) {
212 ccptr->FirstExpressMessage = newmsg;
215 findend = ccptr->FirstExpressMessage;
216 while (findend->next != NULL) {
217 findend = findend->next;
219 findend->next = newmsg;
222 /* If the target context is a session which can handle asynchronous
223 * messages, go ahead and set the flag for that.
225 set_async_waiting(ccptr);
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.
236 int send_instant_message(char *lun, char *lem, char *x_user, char *x_msg)
238 int message_sent = 0; /* number of successful sends */
239 struct CitContext *ccptr;
240 struct ExpressMessage *newmsg = NULL;
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 */
245 if (strlen(x_msg) > 0) {
249 /* find the target user's context and append the message */
250 begin_critical_section(S_SESSION_TABLE);
252 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
254 if (ccptr->fake_username[0]) {
255 un = ccptr->fake_username;
258 un = ccptr->user.fullname;
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)) ) {
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;
275 newmsg->text = strdup(x_msg);
277 add_xmsg_to_context(ccptr, newmsg);
281 log_instant_message(CC, ccptr, newmsg->text, serial_number);
287 end_critical_section(S_SESSION_TABLE);
288 return (message_sent);
292 * send instant messages
294 void cmd_sexp(char *argbuf)
296 int message_sent = 0;
297 char x_user[USERNAME_SIZE];
301 char *x_big_msgbuf = NULL;
303 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
304 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
307 if (CC->fake_username[0])
308 lun = CC->fake_username;
310 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);
363 cprintf("%d Ok to send message", CIT_OK);
364 if (message_sent > 1)
365 cprintf(" to %d users", message_sent);
368 if (CtdlGetUser(NULL, x_user))
369 cprintf("%d '%s' does not exist.\n",
370 ERROR + NO_SUCH_USER, x_user);
372 cprintf("%d '%s' is not logged in "
373 "or is not accepting pages.\n",
374 ERROR + RESOURCE_NOT_OPEN, x_user);
384 * Enter or exit paging-disabled mode
386 void cmd_dexp(char *argbuf)
390 if (CtdlAccessCheck(ac_logged_in)) return;
392 new_state = extract_int(argbuf, 0);
393 if ((new_state == 0) || (new_state == 1)) {
394 CC->disable_exp = new_state;
397 cprintf("%d %d\n", CIT_OK, CC->disable_exp);
402 * Request client termination
404 void cmd_reqt(char *argbuf) {
405 struct CitContext *ccptr;
408 struct ExpressMessage *newmsg;
410 if (CtdlAccessCheck(ac_aide)) return;
411 which_session = extract_int(argbuf, 0);
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)) {
417 newmsg = (struct ExpressMessage *)
418 malloc(sizeof (struct ExpressMessage));
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.");
427 add_xmsg_to_context(ccptr, newmsg);
432 end_critical_section(S_SESSION_TABLE);
433 cprintf("%d Sent termination request to %d sessions.\n", CIT_OK, sessions);
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.
442 void flush_individual_conversation(struct imlog *im) {
443 struct CtdlMessage *msg;
445 char roomname[ROOMNAMELEN];
446 StrBuf *MsgBuf, *FullMsgBuf;
448 StrBufAppendBufPlain(im->conversation, HKEY(
454 MsgBuf = StrBufRFC2047encodeMessage(im->conversation);
455 FlushStrBuf(im->conversation);
456 FullMsgBuf = NewStrBufPlain(NULL, StrLength(im->conversation) + 100);
458 StrBufAppendBufPlain(FullMsgBuf, HKEY(
459 "Content-type: text/html; charset=UTF-8\r\n"
460 "Content-Transfer-Encoding: quoted-printable\r\n"
463 StrBufAppendBuf (FullMsgBuf, MsgBuf, 0);
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]));
474 CM_SetField(msg, eAuthor, HKEY("Citadel"));
476 if (!IsEmptyStr(im->usernames[1])) {
477 CM_SetField(msg, eRecipient, im->usernames[1], strlen(im->usernames[1]));
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 */
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.
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.
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);
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);
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);
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.)
518 void flush_conversations_to_disk(time_t if_older_than) {
520 struct imlog *flush_these = NULL;
521 struct imlog *dont_flush_these = NULL;
522 struct imlog *imptr = NULL;
523 struct CitContext *nptr;
526 nptr = CtdlGetContextArray(&nContexts) ; /* Make a copy of the current wholist */
528 begin_critical_section(S_IM_LOGS);
532 imlist = imlist->next;
534 /* For a two party conversation, if one party has logged out, force flush. */
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;
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 */
547 else { /* one party conversation (yes, people do IM themselves) */
548 if (!user0_is_still_online) {
549 imptr->lastmsg = 0L; /* force flush */
554 /* Now test this conversation to see if it qualifies for flushing. */
555 if ((time(NULL) - imptr->lastmsg) > if_older_than)
557 /* This conversation qualifies. Move it to the list of ones to flush. */
558 imptr->next = flush_these;
562 /* Move it to the list of ones not to flush. */
563 imptr->next = dont_flush_these;
564 dont_flush_these = imptr;
567 imlist = dont_flush_these;
568 end_critical_section(S_IM_LOGS);
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.
574 while (flush_these) {
576 flush_individual_conversation(flush_these); /* This will free the string buffer */
578 flush_these = flush_these->next;
585 void instmsg_timer(void) {
586 flush_conversations_to_disk(300); /* Anything that hasn't peeped in more than 5 minutes */
589 void instmsg_shutdown(void) {
590 flush_conversations_to_disk(0); /* Get it ALL onto disk NOW. */
593 CTDL_MODULE_INIT(instmsg)
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);
608 /* return our module name for the log */