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(
113 "Content-type: text/html\r\n"
114 "Content-transfer-encoding: 7bit\r\n"
121 /* Since it's possible for this function to get called more than once if a user is logged
122 * in on multiple sessions, we use the message's serial number to keep track of whether
123 * we've already logged it.
125 if (this_im->last_serial != serial_number)
127 this_im->lastmsg = time(NULL); /* Touch the timestamp so we know when to flush */
128 this_im->last_serial = serial_number;
129 StrBufAppendBufPlain(this_im->conversation, HKEY("<p><b>"), 0);
130 StrBufAppendBufPlain(this_im->conversation, me->user.fullname, -1, 0);
131 StrBufAppendBufPlain(this_im->conversation, HKEY(":</b> "), 0);
132 StrEscAppend(this_im->conversation, NULL, msgtext, 0, 0);
133 StrBufAppendBufPlain(this_im->conversation, HKEY("</p>\r\n"), 0);
135 end_critical_section(S_IM_LOGS);
140 * Delete any remaining instant messages
142 void delete_instant_messages(void) {
143 struct ExpressMessage *ptr;
145 begin_critical_section(S_SESSION_TABLE);
146 while (CC->FirstExpressMessage != NULL) {
147 ptr = CC->FirstExpressMessage->next;
148 if (CC->FirstExpressMessage->text != NULL)
149 free(CC->FirstExpressMessage->text);
150 free(CC->FirstExpressMessage);
151 CC->FirstExpressMessage = ptr;
153 end_critical_section(S_SESSION_TABLE);
159 * Retrieve instant messages
161 void cmd_gexp(char *argbuf) {
162 struct ExpressMessage *ptr;
164 if (CC->FirstExpressMessage == NULL) {
165 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
169 begin_critical_section(S_SESSION_TABLE);
170 ptr = CC->FirstExpressMessage;
171 CC->FirstExpressMessage = CC->FirstExpressMessage->next;
172 end_critical_section(S_SESSION_TABLE);
174 cprintf("%d %d|%ld|%d|%s|%s|%s\n",
176 ((ptr->next != NULL) ? 1 : 0), /* more msgs? */
177 (long)ptr->timestamp, /* time sent */
178 ptr->flags, /* flags */
179 ptr->sender, /* sender of msg */
180 config.c_nodename, /* static for now (and possibly deprecated) */
181 ptr->sender_email /* email or jid of sender */
184 if (ptr->text != NULL) {
185 memfmout(ptr->text, "\n");
194 * Asynchronously deliver instant messages
196 void cmd_gexp_async(void) {
198 /* Only do this if the session can handle asynchronous protocol */
199 if (CC->is_async == 0) return;
201 /* And don't do it if there's nothing to send. */
202 if (CC->FirstExpressMessage == NULL) return;
204 cprintf("%d instant msg\n", ASYNC_MSG + ASYNC_GEXP);
208 * Back end support function for send_instant_message() and company
210 void add_xmsg_to_context(struct CitContext *ccptr, struct ExpressMessage *newmsg)
212 struct ExpressMessage *findend;
214 if (ccptr->FirstExpressMessage == NULL) {
215 ccptr->FirstExpressMessage = newmsg;
218 findend = ccptr->FirstExpressMessage;
219 while (findend->next != NULL) {
220 findend = findend->next;
222 findend->next = newmsg;
225 /* If the target context is a session which can handle asynchronous
226 * messages, go ahead and set the flag for that.
228 set_async_waiting(ccptr);
235 * This is the back end to the instant message sending function.
236 * Returns the number of users to which the message was sent.
237 * Sending a zero-length message tests for recipients without sending messages.
239 int send_instant_message(char *lun, char *lem, char *x_user, char *x_msg)
241 int message_sent = 0; /* number of successful sends */
242 struct CitContext *ccptr;
243 struct ExpressMessage *newmsg = NULL;
245 int do_send = 0; /* 1 = send message; 0 = only check for valid recipient */
246 static int serial_number = 0; /* this keeps messages from getting logged twice */
248 if (strlen(x_msg) > 0) {
252 /* find the target user's context and append the message */
253 begin_critical_section(S_SESSION_TABLE);
255 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
257 if (ccptr->fake_username[0]) {
258 un = ccptr->fake_username;
261 un = ccptr->user.fullname;
264 if ( ((!strcasecmp(un, x_user))
265 || (!strcasecmp(x_user, "broadcast")))
266 && (ccptr->can_receive_im)
267 && ((ccptr->disable_exp == 0)
268 || (CC->user.axlevel >= AxAideU)) ) {
270 newmsg = (struct ExpressMessage *) malloc(sizeof (struct ExpressMessage));
271 memset(newmsg, 0, sizeof (struct ExpressMessage));
272 time(&(newmsg->timestamp));
273 safestrncpy(newmsg->sender, lun, sizeof newmsg->sender);
274 safestrncpy(newmsg->sender_email, lem, sizeof newmsg->sender_email);
275 if (!strcasecmp(x_user, "broadcast")) {
276 newmsg->flags |= EM_BROADCAST;
278 newmsg->text = strdup(x_msg);
280 add_xmsg_to_context(ccptr, newmsg);
284 log_instant_message(CC, ccptr, newmsg->text, serial_number);
290 end_critical_section(S_SESSION_TABLE);
291 return (message_sent);
295 * send instant messages
297 void cmd_sexp(char *argbuf)
299 int message_sent = 0;
300 char x_user[USERNAME_SIZE];
304 char *x_big_msgbuf = NULL;
306 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
307 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
310 if (CC->fake_username[0])
311 lun = CC->fake_username;
313 lun = CC->user.fullname;
315 lem = CC->cs_inet_email;
317 extract_token(x_user, argbuf, 0, '|', sizeof x_user);
318 extract_token(x_msg, argbuf, 1, '|', sizeof x_msg);
321 cprintf("%d You were not previously paged.\n", ERROR + NO_SUCH_USER);
324 if ((!strcasecmp(x_user, "broadcast")) && (CC->user.axlevel < AxAideU)) {
325 cprintf("%d Higher access required to send a broadcast.\n",
326 ERROR + HIGHER_ACCESS_REQUIRED);
329 /* This loop handles text-transfer pages */
330 if (!strcmp(x_msg, "-")) {
331 message_sent = PerformXmsgHooks(lun, lem, x_user, "");
332 if (message_sent == 0) {
333 if (CtdlGetUser(NULL, x_user))
334 cprintf("%d '%s' does not exist.\n",
335 ERROR + NO_SUCH_USER, x_user);
337 cprintf("%d '%s' is not logged in "
338 "or is not accepting pages.\n",
339 ERROR + RESOURCE_NOT_OPEN, x_user);
343 cprintf("%d Transmit message (will deliver to %d users)\n",
344 SEND_LISTING, message_sent);
345 x_big_msgbuf = malloc(SIZ);
346 memset(x_big_msgbuf, 0, SIZ);
347 while (client_getln(x_msg, sizeof x_msg) >= 0 && strcmp(x_msg, "000")) {
348 x_big_msgbuf = realloc(x_big_msgbuf,
349 strlen(x_big_msgbuf) + strlen(x_msg) + 4);
350 if (!IsEmptyStr(x_big_msgbuf))
351 if (x_big_msgbuf[strlen(x_big_msgbuf)] != '\n')
352 strcat(x_big_msgbuf, "\n");
353 strcat(x_big_msgbuf, x_msg);
355 PerformXmsgHooks(lun, lem, x_user, x_big_msgbuf);
358 /* This loop handles inline pages */
360 message_sent = PerformXmsgHooks(lun, lem, x_user, x_msg);
362 if (message_sent > 0) {
363 if (!IsEmptyStr(x_msg))
364 cprintf("%d Message sent", CIT_OK);
366 cprintf("%d Ok to send message", CIT_OK);
367 if (message_sent > 1)
368 cprintf(" to %d users", message_sent);
371 if (CtdlGetUser(NULL, x_user))
372 cprintf("%d '%s' does not exist.\n",
373 ERROR + NO_SUCH_USER, x_user);
375 cprintf("%d '%s' is not logged in "
376 "or is not accepting pages.\n",
377 ERROR + RESOURCE_NOT_OPEN, x_user);
387 * Enter or exit paging-disabled mode
389 void cmd_dexp(char *argbuf)
393 if (CtdlAccessCheck(ac_logged_in)) return;
395 new_state = extract_int(argbuf, 0);
396 if ((new_state == 0) || (new_state == 1)) {
397 CC->disable_exp = new_state;
400 cprintf("%d %d\n", CIT_OK, CC->disable_exp);
405 * Request client termination
407 void cmd_reqt(char *argbuf) {
408 struct CitContext *ccptr;
411 struct ExpressMessage *newmsg;
413 if (CtdlAccessCheck(ac_aide)) return;
414 which_session = extract_int(argbuf, 0);
416 begin_critical_section(S_SESSION_TABLE);
417 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
418 if ((ccptr->cs_pid == which_session) || (which_session == 0)) {
420 newmsg = (struct ExpressMessage *)
421 malloc(sizeof (struct ExpressMessage));
423 sizeof (struct ExpressMessage));
424 time(&(newmsg->timestamp));
425 safestrncpy(newmsg->sender, CC->user.fullname,
426 sizeof newmsg->sender);
427 newmsg->flags |= EM_GO_AWAY;
428 newmsg->text = strdup("Automatic logoff requested.");
430 add_xmsg_to_context(ccptr, newmsg);
435 end_critical_section(S_SESSION_TABLE);
436 cprintf("%d Sent termination request to %d sessions.\n", CIT_OK, sessions);
441 * This is the back end for flush_conversations_to_disk()
442 * At this point we've isolated a single conversation (struct imlog)
443 * and are ready to write it to disk.
445 void flush_individual_conversation(struct imlog *im) {
446 struct CtdlMessage *msg;
448 char roomname[ROOMNAMELEN];
450 StrBufAppendBufPlain(im->conversation, HKEY(
456 msg = malloc(sizeof(struct CtdlMessage));
457 memset(msg, 0, sizeof(struct CtdlMessage));
458 msg->cm_magic = CTDLMESSAGE_MAGIC;
459 msg->cm_anon_type = MES_NORMAL;
460 msg->cm_format_type = FMT_RFC822;
461 if (!IsEmptyStr(im->usernames[0])) {
462 msg->cm_fields['A'] = strdup(im->usernames[0]);
464 msg->cm_fields['A'] = strdup("Citadel");
466 if (!IsEmptyStr(im->usernames[1])) {
467 msg->cm_fields['R'] = strdup(im->usernames[1]);
469 msg->cm_fields['O'] = strdup(PAGELOGROOM);
470 msg->cm_fields['N'] = strdup(NODENAME);
471 msg->cm_fields['M'] = SmashStrBuf(&im->conversation); /* we own this memory now */
473 /* Start with usernums[1] because it's guaranteed to be higher than usernums[0],
474 * so if there's only one party, usernums[0] will be zero but usernums[1] won't.
475 * Create the room if necessary. Note that we create as a type 5 room rather
476 * than 4, which indicates that it's a personal room but we've already supplied
477 * the namespace prefix.
479 * In the unlikely event that usernums[1] is zero, a room with an invalid namespace
480 * prefix will be created. That's ok because the auto-purger will clean it up later.
482 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[1], PAGELOGROOM);
483 CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
484 msgnum = CtdlSubmitMsg(msg, NULL, roomname, 0);
485 CtdlFreeMessage(msg);
487 /* If there is a valid user number in usernums[0], save a copy for them too. */
488 if (im->usernums[0] > 0) {
489 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[0], PAGELOGROOM);
490 CtdlCreateRoom(roomname, 5, "", 0, 1, 1, VIEW_BBS);
491 CtdlSaveMsgPointerInRoom(roomname, msgnum, 0, NULL);
494 /* Finally, if we're logging instant messages globally, do that now. */
495 if (!IsEmptyStr(config.c_logpages)) {
496 CtdlCreateRoom(config.c_logpages, 3, "", 0, 1, 1, VIEW_BBS);
497 CtdlSaveMsgPointerInRoom(config.c_logpages, msgnum, 0, NULL);
503 * Locate instant message conversations which have gone idle
504 * (or, if the server is shutting down, locate *all* conversations)
505 * and flush them to disk (in the participants' log rooms, etc.)
507 void flush_conversations_to_disk(time_t if_older_than) {
509 struct imlog *flush_these = NULL;
510 struct imlog *dont_flush_these = NULL;
511 struct imlog *imptr = NULL;
512 struct CitContext *nptr;
515 nptr = CtdlGetContextArray(&nContexts) ; /* Make a copy of the current wholist */
517 begin_critical_section(S_IM_LOGS);
521 imlist = imlist->next;
523 /* For a two party conversation, if one party has logged out, force flush. */
525 int user0_is_still_online = 0;
526 int user1_is_still_online = 0;
527 for (i=0; i<nContexts; i++) {
528 if (nptr[i].user.usernum == imptr->usernums[0]) ++user0_is_still_online;
529 if (nptr[i].user.usernum == imptr->usernums[1]) ++user1_is_still_online;
531 if (imptr->usernums[0] != imptr->usernums[1]) { /* two party conversation */
532 if ((!user0_is_still_online) || (!user1_is_still_online)) {
533 imptr->lastmsg = 0L; /* force flush */
536 else { /* one party conversation (yes, people do IM themselves) */
537 if (!user0_is_still_online) {
538 imptr->lastmsg = 0L; /* force flush */
543 /* Now test this conversation to see if it qualifies for flushing. */
544 if ((time(NULL) - imptr->lastmsg) > if_older_than)
546 /* This conversation qualifies. Move it to the list of ones to flush. */
547 imptr->next = flush_these;
551 /* Move it to the list of ones not to flush. */
552 imptr->next = dont_flush_these;
553 dont_flush_these = imptr;
556 imlist = dont_flush_these;
557 end_critical_section(S_IM_LOGS);
560 /* We are now outside of the critical section, and we are the only thread holding a
561 * pointer to a linked list of conversations to be flushed to disk.
563 while (flush_these) {
565 flush_individual_conversation(flush_these); /* This will free the string buffer */
567 flush_these = flush_these->next;
574 void instmsg_timer(void) {
575 flush_conversations_to_disk(300); /* Anything that hasn't peeped in more than 5 minutes */
578 void instmsg_shutdown(void) {
579 flush_conversations_to_disk(0); /* Get it ALL onto disk NOW. */
582 CTDL_MODULE_INIT(instmsg)
586 CtdlRegisterProtoHook(cmd_gexp, "GEXP", "Get instant messages");
587 CtdlRegisterProtoHook(cmd_sexp, "SEXP", "Send an instant message");
588 CtdlRegisterProtoHook(cmd_dexp, "DEXP", "Disable instant messages");
589 CtdlRegisterProtoHook(cmd_reqt, "REQT", "Request client termination");
590 CtdlRegisterSessionHook(cmd_gexp_async, EVT_ASYNC, PRIO_ASYNC + 1);
591 CtdlRegisterSessionHook(delete_instant_messages, EVT_STOP, PRIO_STOP + 1);
592 CtdlRegisterXmsgHook(send_instant_message, XMSG_PRI_LOCAL);
593 CtdlRegisterSessionHook(instmsg_timer, EVT_TIMER, PRIO_CLEANUP + 400);
594 CtdlRegisterSessionHook(instmsg_shutdown, EVT_SHUTDOWN, PRIO_SHUTDOWN + 10);
597 /* return our module name for the log */