* More license declarations
[citadel.git] / citadel / modules / chat / serv_chat.c
1 /*
2  * $Id$
3  * 
4  * This module handles all "real time" communication between users.  The
5  * modes of communication currently supported are Chat and Paging.
6  *
7  * Copyright (c) 1987-2009 by the citadel.org team
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24 #include "sysdep.h"
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <sys/types.h>
33
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <sys/wait.h>
46 #include <string.h>
47 #include <limits.h>
48 #include <libcitadel.h>
49 #include "citadel.h"
50 #include "server.h"
51 #include "serv_chat.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "msgbase.h"
56 #include "user_ops.h"
57 #include "room_ops.h"
58
59 #ifndef HAVE_SNPRINTF
60 #include "snprintf.h"
61 #endif
62
63 #include "ctdl_module.h"
64
65 struct ChatLine *ChatQueue = NULL;
66 int ChatLastMsg = 0;
67
68 struct imlog {
69         struct imlog *next;
70         long usernums[2];
71         char usernames[2][128];
72         time_t lastmsg;
73         int last_serial;
74         StrBuf *conversation;
75 };
76
77 struct imlog *imlist = NULL;
78
79 /*
80  * This function handles the logging of instant messages to disk.
81  */
82 void log_instant_message(struct CitContext *me, struct CitContext *them, char *msgtext, int serial_number)
83 {
84         long usernums[2];
85         long t;
86         struct imlog *iptr = NULL;
87         struct imlog *this_im = NULL;
88         
89         memset(usernums, 0, sizeof usernums);
90         usernums[0] = me->user.usernum;
91         usernums[1] = them->user.usernum;
92
93         /* Always put the lower user number first, so we can use the array as a hash value which
94          * represents a pair of users.  For a broadcast message one of the users will be 0.
95          */
96         if (usernums[0] > usernums[1]) {
97                 t = usernums[0];
98                 usernums[0] = usernums[1];
99                 usernums[1] = t;
100         }
101
102         begin_critical_section(S_IM_LOGS);
103
104         /* Look for an existing conversation in the hash table.
105          * If not found, create a new one.
106          */
107
108         this_im = NULL;
109         for (iptr = imlist; iptr != NULL; iptr = iptr->next) {
110                 if ((iptr->usernums[0] == usernums[0]) && (iptr->usernums[1] == usernums[1])) {
111                         /* Existing conversation */
112                         this_im = iptr;
113                 }
114         }
115         if (this_im == NULL) {
116                 /* New conversation */
117                 this_im = malloc(sizeof(struct imlog));
118                 memset(this_im, 0, sizeof (struct imlog));
119                 this_im->usernums[0] = usernums[0];
120                 this_im->usernums[1] = usernums[1];
121                 /* usernames[] and usernums[] might not be in the same order.  This is not an error. */
122                 if (me) {
123                         safestrncpy(this_im->usernames[0], me->user.fullname, sizeof this_im->usernames[0]);
124                 }
125                 if (them) {
126                         safestrncpy(this_im->usernames[1], them->user.fullname, sizeof this_im->usernames[1]);
127                 }
128                 this_im->conversation = NewStrBuf();
129                 this_im->next = imlist;
130                 imlist = this_im;
131                 StrBufAppendBufPlain(this_im->conversation, HKEY(
132                         "Content-type: text/html\r\n"
133                         "Content-transfer-encoding: 7bit\r\n"
134                         "\r\n"
135                         "<html><body>\r\n"
136                         ), 0);
137         }
138
139
140         /* Since it's possible for this function to get called more than once if a user is logged
141          * in on multiple sessions, we use the message's serial number to keep track of whether
142          * we've already logged it.
143          */
144         if (this_im->last_serial != serial_number)
145         {
146                 this_im->lastmsg = time(NULL);          /* Touch the timestamp so we know when to flush */
147                 this_im->last_serial = serial_number;
148                 StrBufAppendBufPlain(this_im->conversation, HKEY("<p><b>"), 0);
149                 StrBufAppendBufPlain(this_im->conversation, me->user.fullname, -1, 0);
150                 StrBufAppendBufPlain(this_im->conversation, HKEY(":</b> "), 0);
151                 StrEscAppend(this_im->conversation, NULL, msgtext, 0, 0);
152                 StrBufAppendBufPlain(this_im->conversation, HKEY("</p>\r\n"), 0);
153         }
154         end_critical_section(S_IM_LOGS);
155 }
156
157 /*
158  * This message can be set to anything you want, but it is
159  * checked for consistency so don't move it away from here.
160  */
161 #define KICKEDMSG "You have been kicked out of this room."
162
163 void allwrite(char *cmdbuf, int flag, char *username)
164 {
165         FILE *fp;
166         char bcast[SIZ];
167         char *un;
168         struct ChatLine *clptr, *clnew;
169         time_t now;
170
171         if (CC->fake_username[0])
172                 un = CC->fake_username;
173         else
174                 un = CC->user.fullname;
175         if (flag == 1) {
176                 snprintf(bcast, sizeof bcast, ":|<%s %s>", un, cmdbuf);
177         } else if (flag == 0) {
178                 snprintf(bcast, sizeof bcast, "%s|%s", un, cmdbuf);
179         } else if (flag == 2) {
180                 snprintf(bcast, sizeof bcast, ":|<%s whispers %s>", un, cmdbuf);
181         } else if (flag == 3) {
182                 snprintf(bcast, sizeof bcast, ":|%s", KICKEDMSG);
183         }
184         if ((strcasecmp(cmdbuf, "NOOP")) && (flag != 2)) {
185                 fp = fopen(CHATLOG, "a");
186                 if (fp != NULL)
187                         fprintf(fp, "%s\n", bcast);
188                 fclose(fp);
189         }
190         clnew = (struct ChatLine *) malloc(sizeof(struct ChatLine));
191         memset(clnew, 0, sizeof(struct ChatLine));
192         if (clnew == NULL) {
193                 fprintf(stderr, "citserver: cannot alloc chat line: %s\n",
194                         strerror(errno));
195                 return;
196         }
197         time(&now);
198         clnew->next = NULL;
199         clnew->chat_time = now;
200         safestrncpy(clnew->chat_room, CC->room.QRname,
201                         sizeof clnew->chat_room);
202         clnew->chat_room[sizeof clnew->chat_room - 1] = 0;
203         if (username) {
204                 safestrncpy(clnew->chat_username, username,
205                         sizeof clnew->chat_username);
206                 clnew->chat_username[sizeof clnew->chat_username - 1] = 0;
207         } else
208                 clnew->chat_username[0] = '\0';
209         safestrncpy(clnew->chat_text, bcast, sizeof clnew->chat_text);
210
211         /* Here's the critical section.
212          * First, add the new message to the queue...
213          */
214         begin_critical_section(S_CHATQUEUE);
215         ++ChatLastMsg;
216         clnew->chat_seq = ChatLastMsg;
217         if (ChatQueue == NULL) {
218                 ChatQueue = clnew;
219         } else {
220                 for (clptr = ChatQueue; clptr->next != NULL; clptr = clptr->next);;
221                 clptr->next = clnew;
222         }
223
224         /* Then, before releasing the lock, free the expired messages */
225         while ((ChatQueue != NULL) && (now - ChatQueue->chat_time >= 120L)) {
226                 clptr = ChatQueue;
227                 ChatQueue = ChatQueue->next;
228                 free(clptr);
229         }
230         end_critical_section(S_CHATQUEUE);
231 }
232
233
234 t_context *find_context(char **unstr)
235 {
236         t_context *t_cc, *found_cc = NULL;
237         char *name, *tptr;
238
239         if ((!*unstr) || (!unstr))
240                 return (NULL);
241
242         begin_critical_section(S_SESSION_TABLE);
243         for (t_cc = ContextList; ((t_cc) && (!found_cc)); t_cc = t_cc->next) {
244                 if (t_cc->fake_username[0])
245                         name = t_cc->fake_username;
246                 else
247                         name = t_cc->curr_user;
248                 tptr = *unstr;
249                 if ((!strncasecmp(name, tptr, strlen(name))) && (tptr[strlen(name)] == ' ')) {
250                         found_cc = t_cc;
251                         *unstr = &(tptr[strlen(name) + 1]);
252                 }
253         }
254         end_critical_section(S_SESSION_TABLE);
255
256         return (found_cc);
257 }
258
259 /*
260  * List users in chat.
261  * allflag ==   0 = list users in chat
262  *              1 = list users in chat, followed by users not in chat
263  *              2 = display count only
264  */
265
266 void do_chat_listing(int allflag)
267 {
268         struct CitContext *ccptr;
269         int count = 0;
270         int count_elsewhere = 0;
271         char roomname[ROOMNAMELEN];
272
273         if ((allflag == 0) || (allflag == 1))
274                 cprintf(":|\n:| Users currently in chat:\n");
275         begin_critical_section(S_SESSION_TABLE);
276         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
277                 if (ccptr->cs_flags & CS_CHAT) {
278                         if (!strcasecmp(ccptr->room.QRname,
279                            CC->room.QRname)) {
280                                 ++count;
281                         }
282                         else {
283                                 ++count_elsewhere;
284                         }
285                 }
286
287                 GenerateRoomDisplay(roomname, ccptr, CC);
288                 if ((CC->user.axlevel < 6) && (!IsEmptyStr(ccptr->fake_roomname))) {
289                         strcpy(roomname, ccptr->fake_roomname);
290                 }
291
292                 if ((ccptr->cs_flags & CS_CHAT) && ((ccptr->cs_flags & CS_STEALTH) == 0)) {
293                         if ((allflag == 0) || (allflag == 1)) {
294                                 cprintf(":| %-25s <%s>:\n",
295                                         (ccptr->fake_username[0]) ? ccptr->fake_username : ccptr->curr_user,
296                                         roomname);
297                         }
298                 }
299         }
300
301         if (allflag == 1) {
302                 cprintf(":|\n:| Users not in chat:\n");
303                 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
304
305                         GenerateRoomDisplay(roomname, ccptr, CC);
306                         if ((CC->user.axlevel < 6)
307                         && (!IsEmptyStr(ccptr->fake_roomname))) {
308                                 strcpy(roomname, ccptr->fake_roomname);
309                         }
310
311                         if (((ccptr->cs_flags & CS_CHAT) == 0)
312                             && ((ccptr->cs_flags & CS_STEALTH) == 0)) {
313                                 cprintf(":| %-25s <%s>:\n",
314                                         (ccptr->fake_username[0]) ? ccptr->fake_username : ccptr->curr_user,
315                                         roomname);
316                         }
317                 }
318         }
319         end_critical_section(S_SESSION_TABLE);
320
321         if (allflag == 2) {
322                 if (count > 1) {
323                         cprintf(":|There are %d users here.\n", count);
324                 }
325                 else {
326                         cprintf(":|Note: you are the only one here.\n");
327                 }
328                 if (count_elsewhere > 0) {
329                         cprintf(":|There are %d users chatting in other rooms.\n", count_elsewhere);
330                 }
331         }
332
333         cprintf(":|\n");
334 }
335
336
337 void cmd_chat(char *argbuf)
338 {
339         char cmdbuf[SIZ];
340         char *un;
341         char *strptr1;
342         int MyLastMsg, ThisLastMsg;
343         struct ChatLine *clptr;
344         struct CitContext *t_context;
345         int retval;
346
347         if (!(CC->logged_in)) {
348                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
349                 return;
350         }
351
352         CC->cs_flags = CC->cs_flags | CS_CHAT;
353         cprintf("%d Entering chat mode (type '/help' for available commands)\n",
354                 START_CHAT_MODE);
355         unbuffer_output();
356
357         MyLastMsg = ChatLastMsg;
358
359         if ((CC->cs_flags & CS_STEALTH) == 0) {
360                 allwrite("<entering chat>", 0, NULL);
361         }
362         strcpy(cmdbuf, "");
363
364         do_chat_listing(2);
365
366         while (1) {
367                 int ok_cmd;
368                 int linelen;
369
370                 ok_cmd = 0;
371                 linelen = strlen(cmdbuf);
372                 if (linelen > 100) --linelen;   /* truncate too-long lines */
373                 cmdbuf[linelen + 1] = 0;
374
375                 retval = client_read_to(&cmdbuf[linelen], 1, 2);
376
377                 if (retval < 0 || CC->kill_me) {        /* socket broken? */
378                         if ((CC->cs_flags & CS_STEALTH) == 0) {
379                                 allwrite("<disconnected>", 0, NULL);
380                         }
381                         return;
382                 }
383
384                 /* if we have a complete line, do send processing */
385                 if (!IsEmptyStr(cmdbuf))
386                         if (cmdbuf[strlen(cmdbuf) - 1] == 10) {
387                                 cmdbuf[strlen(cmdbuf) - 1] = 0;
388                                 time(&CC->lastcmd);
389                                 time(&CC->lastidle);
390
391                                 if ((!strcasecmp(cmdbuf, "exit"))
392                                     || (!strcasecmp(cmdbuf, "/exit"))
393                                     || (!strcasecmp(cmdbuf, "quit"))
394                                     || (!strcasecmp(cmdbuf, "logout"))
395                                     || (!strcasecmp(cmdbuf, "logoff"))
396                                     || (!strcasecmp(cmdbuf, "/q"))
397                                     || (!strcasecmp(cmdbuf, ".q"))
398                                     || (!strcasecmp(cmdbuf, "/quit"))
399                                     )
400                                         strcpy(cmdbuf, "000");
401
402                                 if (!strcmp(cmdbuf, "000")) {
403                                         if ((CC->cs_flags & CS_STEALTH) == 0) {
404                                                 allwrite("<exiting chat>", 0, NULL);
405                                         }
406                                         sleep(1);
407                                         cprintf("000\n");
408                                         CC->cs_flags = CC->cs_flags - CS_CHAT;
409                                         return;
410                                 }
411                                 if ((!strcasecmp(cmdbuf, "/help"))
412                                     || (!strcasecmp(cmdbuf, "help"))
413                                     || (!strcasecmp(cmdbuf, "/?"))
414                                     || (!strcasecmp(cmdbuf, "?"))) {
415                                         cprintf(":|\n");
416                                         cprintf(":|Available commands: \n");
417                                         cprintf(":|/help   (prints this message) \n");
418                                         cprintf(":|/who    (list users currently in chat) \n");
419                                         cprintf(":|/whobbs (list users in chat -and- elsewhere) \n");
420                                         cprintf(":|/me     ('action' line, ala irc) \n");
421                                         cprintf(":|/msg    (send private message, ala irc) \n");
422                                         if (is_room_aide()) {
423                                                 cprintf(":|/kick   (kick another user out of this room) \n");
424                                         }
425                                         cprintf(":|/quit   (exit from this chat) \n");
426                                         cprintf(":|\n");
427                                         ok_cmd = 1;
428                                 }
429                                 if (!strcasecmp(cmdbuf, "/who")) {
430                                         do_chat_listing(0);
431                                         ok_cmd = 1;
432                                 }
433                                 if (!strcasecmp(cmdbuf, "/whobbs")) {
434                                         do_chat_listing(1);
435                                         ok_cmd = 1;
436                                 }
437                                 if (!strncasecmp(cmdbuf, "/me ", 4)) {
438                                         allwrite(&cmdbuf[4], 1, NULL);
439                                         ok_cmd = 1;
440                                 }
441                                 if (!strncasecmp(cmdbuf, "/msg ", 5)) {
442                                         ok_cmd = 1;
443                                         strptr1 = &cmdbuf[5];
444                                         if ((t_context = find_context(&strptr1))) {
445                                                 allwrite(strptr1, 2, CC->curr_user);
446                                                 if (strcasecmp(CC->curr_user, t_context->curr_user))
447                                                         allwrite(strptr1, 2, t_context->curr_user);
448                                         } else
449                                                 cprintf(":|User not found.\n");
450                                         cprintf("\n");
451                                 }
452                                 /* The /kick function is implemented by sending a specific
453                                  * message to the kicked-out user's context.  When that message
454                                  * is processed by the read loop, that context will exit.
455                                  */
456                                 if ( (!strncasecmp(cmdbuf, "/kick ", 6)) && (is_room_aide()) ) {
457                                         ok_cmd = 1;
458                                         strptr1 = &cmdbuf[6];
459                                         strcat(strptr1, " ");
460                                         if ((t_context = find_context(&strptr1))) {
461                                                 if (strcasecmp(CC->curr_user, t_context->curr_user))
462                                                         allwrite(strptr1, 3, t_context->curr_user);
463                                         } else
464                                                 cprintf(":|User not found.\n");
465                                         cprintf("\n");
466                                 }
467                                 if ((cmdbuf[0] != '/') && (strlen(cmdbuf) > 0)) {
468                                         ok_cmd = 1;
469                                         allwrite(cmdbuf, 0, NULL);
470                                 }
471                                 if ((!ok_cmd) && (cmdbuf[0]) && (cmdbuf[0] != '\n'))
472                                         cprintf(":|Command %s is not understood.\n", cmdbuf);
473
474                                 strcpy(cmdbuf, "");
475
476                         }
477                 /* now check the queue for new incoming stuff */
478
479                 if (CC->fake_username[0])
480                         un = CC->fake_username;
481                 else
482                         un = CC->curr_user;
483                 if (ChatLastMsg > MyLastMsg) {
484                         ThisLastMsg = ChatLastMsg;
485                         for (clptr = ChatQueue; clptr != NULL; clptr = clptr->next) {
486                                 if ((clptr->chat_seq > MyLastMsg) && ((!clptr->chat_username[0]) || (!strncasecmp(un, clptr->chat_username, 32)))) {
487                                         if ((!clptr->chat_room[0]) || (!strncasecmp(CC->room.QRname, clptr->chat_room, ROOMNAMELEN))) {
488                                                 /* Output new chat data */
489                                                 cprintf("%s\n", clptr->chat_text);
490
491                                                 /* See if we've been force-quitted (kicked etc.) */
492                                                 if (!strcmp(&clptr->chat_text[2], KICKEDMSG)) {
493                                                         allwrite("<kicked out of this room>", 0, NULL);
494                                                         cprintf("000\n");
495                                                         CC->cs_flags = CC->cs_flags - CS_CHAT;
496
497                                                         /* Kick user out of room */
498                                                         CtdlInvtKick(CC->user.fullname, 0);
499
500                                                         /* And return to the Lobby */
501                                                         usergoto(config.c_baseroom, 0, 0, NULL, NULL);
502                                                         return;
503                                                 }
504                                         }
505                                 }
506                         }
507                         MyLastMsg = ThisLastMsg;
508                 }
509         }
510 }
511
512
513
514 /*
515  * Delete any remaining instant messages
516  */
517 void delete_instant_messages(void) {
518         struct ExpressMessage *ptr;
519
520         begin_critical_section(S_SESSION_TABLE);
521         while (CC->FirstExpressMessage != NULL) {
522                 ptr = CC->FirstExpressMessage->next;
523                 if (CC->FirstExpressMessage->text != NULL)
524                         free(CC->FirstExpressMessage->text);
525                 free(CC->FirstExpressMessage);
526                 CC->FirstExpressMessage = ptr;
527         }
528         end_critical_section(S_SESSION_TABLE);
529 }
530
531
532
533
534 /*
535  * Poll for instant messages (OLD METHOD -- ***DEPRECATED ***)
536  */
537 void cmd_pexp(char *argbuf)
538 {
539         struct ExpressMessage *ptr, *holdptr;
540
541         if (CC->FirstExpressMessage == NULL) {
542                 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
543                 return;
544         }
545         begin_critical_section(S_SESSION_TABLE);
546         ptr = CC->FirstExpressMessage;
547         CC->FirstExpressMessage = NULL;
548         end_critical_section(S_SESSION_TABLE);
549
550         cprintf("%d Express msgs:\n", LISTING_FOLLOWS);
551         while (ptr != NULL) {
552                 if (ptr->flags && EM_BROADCAST)
553                         cprintf("Broadcast message ");
554                 else if (ptr->flags && EM_CHAT)
555                         cprintf("Chat request ");
556                 else if (ptr->flags && EM_GO_AWAY)
557                         cprintf("Please logoff now, as requested ");
558                 else
559                         cprintf("Message ");
560                 cprintf("from %s:\n", ptr->sender);
561                 if (ptr->text != NULL)
562                         memfmout(ptr->text, 0, "\n");
563
564                 holdptr = ptr->next;
565                 if (ptr->text != NULL) free(ptr->text);
566                 free(ptr);
567                 ptr = holdptr;
568         }
569         cprintf("000\n");
570 }
571
572
573 /*
574  * Get instant messages (new method)
575  */
576 void cmd_gexp(char *argbuf) {
577         struct ExpressMessage *ptr;
578
579         if (CC->FirstExpressMessage == NULL) {
580                 cprintf("%d No instant messages waiting.\n", ERROR + MESSAGE_NOT_FOUND);
581                 return;
582         }
583
584         begin_critical_section(S_SESSION_TABLE);
585         ptr = CC->FirstExpressMessage;
586         CC->FirstExpressMessage = CC->FirstExpressMessage->next;
587         end_critical_section(S_SESSION_TABLE);
588
589         cprintf("%d %d|%ld|%d|%s|%s|%s\n",
590                 LISTING_FOLLOWS,
591                 ((ptr->next != NULL) ? 1 : 0),          /* more msgs? */
592                 (long)ptr->timestamp,                   /* time sent */
593                 ptr->flags,                             /* flags */
594                 ptr->sender,                            /* sender of msg */
595                 config.c_nodename,                      /* static for now (and possibly deprecated) */
596                 ptr->sender_email                       /* email or jid of sender */
597         );
598
599         if (ptr->text != NULL) {
600                 memfmout(ptr->text, 0, "\n");
601                 if (ptr->text[strlen(ptr->text)-1] != '\n') cprintf("\n");
602                 free(ptr->text);
603         }
604
605         cprintf("000\n");
606         free(ptr);
607 }
608
609 /*
610  * Asynchronously deliver instant messages
611  */
612 void cmd_gexp_async(void) {
613
614         /* Only do this if the session can handle asynchronous protocol */
615         if (CC->is_async == 0) return;
616
617         /* And don't do it if there's nothing to send. */
618         if (CC->FirstExpressMessage == NULL) return;
619
620         cprintf("%d instant msg\n", ASYNC_MSG + ASYNC_GEXP);
621 }
622
623 /*
624  * Back end support function for send_instant_message() and company
625  */
626 void add_xmsg_to_context(struct CitContext *ccptr, struct ExpressMessage *newmsg) 
627 {
628         struct ExpressMessage *findend;
629
630         if (ccptr->FirstExpressMessage == NULL) {
631                 ccptr->FirstExpressMessage = newmsg;
632         }
633         else {
634                 findend = ccptr->FirstExpressMessage;
635                 while (findend->next != NULL) {
636                         findend = findend->next;
637                 }
638                 findend->next = newmsg;
639         }
640
641         /* If the target context is a session which can handle asynchronous
642          * messages, go ahead and set the flag for that.
643          */
644         if (ccptr->is_async) {
645                 ccptr->async_waiting = 1;
646                 if (ccptr->state == CON_IDLE) {
647                         ccptr->state = CON_READY;
648                 }
649         }
650 }
651
652
653
654
655 /* 
656  * This is the back end to the instant message sending function.  
657  * Returns the number of users to which the message was sent.
658  * Sending a zero-length message tests for recipients without sending messages.
659  */
660 int send_instant_message(char *lun, char *lem, char *x_user, char *x_msg)
661 {
662         int message_sent = 0;           /* number of successful sends */
663         struct CitContext *ccptr;
664         struct ExpressMessage *newmsg = NULL;
665         char *un;
666         size_t msglen = 0;
667         int do_send = 0;                /* 1 = send message; 0 = only check for valid recipient */
668         static int serial_number = 0;   /* this keeps messages from getting logged twice */
669
670         if (strlen(x_msg) > 0) {
671                 msglen = strlen(x_msg) + 4;
672                 do_send = 1;
673         }
674
675         /* find the target user's context and append the message */
676         begin_critical_section(S_SESSION_TABLE);
677         ++serial_number;
678         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
679
680                 if (ccptr->fake_username[0]) {
681                         un = ccptr->fake_username;
682                 }
683                 else {
684                         un = ccptr->user.fullname;
685                 }
686
687                 if ( ((!strcasecmp(un, x_user))
688                     || (!strcasecmp(x_user, "broadcast")))
689                     && (ccptr->can_receive_im)
690                     && ((ccptr->disable_exp == 0)
691                     || (CC->user.axlevel >= 6)) ) {
692                         if (do_send) {
693                                 newmsg = (struct ExpressMessage *) malloc(sizeof (struct ExpressMessage));
694                                 memset(newmsg, 0, sizeof (struct ExpressMessage));
695                                 time(&(newmsg->timestamp));
696                                 safestrncpy(newmsg->sender, lun, sizeof newmsg->sender);
697                                 safestrncpy(newmsg->sender_email, lem, sizeof newmsg->sender_email);
698                                 if (!strcasecmp(x_user, "broadcast")) {
699                                         newmsg->flags |= EM_BROADCAST;
700                                 }
701                                 newmsg->text = strdup(x_msg);
702
703                                 add_xmsg_to_context(ccptr, newmsg);
704
705                                 /* and log it ... */
706                                 if (ccptr != CC) {
707                                         log_instant_message(CC, ccptr, newmsg->text, serial_number);
708                                 }
709                         }
710                         ++message_sent;
711                 }
712         }
713         end_critical_section(S_SESSION_TABLE);
714         return (message_sent);
715 }
716
717 /*
718  * send instant messages
719  */
720 void cmd_sexp(char *argbuf)
721 {
722         int message_sent = 0;
723         char x_user[USERNAME_SIZE];
724         char x_msg[1024];
725         char *lun;
726         char *lem;
727         char *x_big_msgbuf = NULL;
728
729         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
730                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
731                 return;
732         }
733         if (CC->fake_username[0])
734                 lun = CC->fake_username;
735         else
736                 lun = CC->user.fullname;
737
738         lem = CC->cs_inet_email;
739
740         extract_token(x_user, argbuf, 0, '|', sizeof x_user);
741         extract_token(x_msg, argbuf, 1, '|', sizeof x_msg);
742
743         if (!x_user[0]) {
744                 cprintf("%d You were not previously paged.\n", ERROR + NO_SUCH_USER);
745                 return;
746         }
747         if ((!strcasecmp(x_user, "broadcast")) && (CC->user.axlevel < 6)) {
748                 cprintf("%d Higher access required to send a broadcast.\n",
749                         ERROR + HIGHER_ACCESS_REQUIRED);
750                 return;
751         }
752         /* This loop handles text-transfer pages */
753         if (!strcmp(x_msg, "-")) {
754                 message_sent = PerformXmsgHooks(lun, lem, x_user, "");
755                 if (message_sent == 0) {
756                         if (getuser(NULL, x_user))
757                                 cprintf("%d '%s' does not exist.\n",
758                                                 ERROR + NO_SUCH_USER, x_user);
759                         else
760                                 cprintf("%d '%s' is not logged in "
761                                                 "or is not accepting pages.\n",
762                                                 ERROR + RESOURCE_NOT_OPEN, x_user);
763                         return;
764                 }
765                 unbuffer_output();
766                 cprintf("%d Transmit message (will deliver to %d users)\n",
767                         SEND_LISTING, message_sent);
768                 x_big_msgbuf = malloc(SIZ);
769                 memset(x_big_msgbuf, 0, SIZ);
770                 while (client_getln(x_msg, sizeof x_msg) >= 0 && strcmp(x_msg, "000")) {
771                         x_big_msgbuf = realloc(x_big_msgbuf,
772                                strlen(x_big_msgbuf) + strlen(x_msg) + 4);
773                         if (!IsEmptyStr(x_big_msgbuf))
774                            if (x_big_msgbuf[strlen(x_big_msgbuf)] != '\n')
775                                 strcat(x_big_msgbuf, "\n");
776                         strcat(x_big_msgbuf, x_msg);
777                 }
778                 PerformXmsgHooks(lun, lem, x_user, x_big_msgbuf);
779                 free(x_big_msgbuf);
780
781                 /* This loop handles inline pages */
782         } else {
783                 message_sent = PerformXmsgHooks(lun, lem, x_user, x_msg);
784
785                 if (message_sent > 0) {
786                         if (!IsEmptyStr(x_msg))
787                                 cprintf("%d Message sent", CIT_OK);
788                         else
789                                 cprintf("%d Ok to send message", CIT_OK);
790                         if (message_sent > 1)
791                                 cprintf(" to %d users", message_sent);
792                         cprintf(".\n");
793                 } else {
794                         if (getuser(NULL, x_user))
795                                 cprintf("%d '%s' does not exist.\n",
796                                                 ERROR + NO_SUCH_USER, x_user);
797                         else
798                                 cprintf("%d '%s' is not logged in "
799                                                 "or is not accepting pages.\n",
800                                                 ERROR + RESOURCE_NOT_OPEN, x_user);
801                 }
802
803
804         }
805 }
806
807
808
809 /*
810  * Enter or exit paging-disabled mode
811  */
812 void cmd_dexp(char *argbuf)
813 {
814         int new_state;
815
816         if (CtdlAccessCheck(ac_logged_in)) return;
817
818         new_state = extract_int(argbuf, 0);
819         if ((new_state == 0) || (new_state == 1)) {
820                 CC->disable_exp = new_state;
821         }
822
823         cprintf("%d %d\n", CIT_OK, CC->disable_exp);
824 }
825
826
827 /*
828  * Request client termination
829  */
830 void cmd_reqt(char *argbuf) {
831         struct CitContext *ccptr;
832         int sessions = 0;
833         int which_session;
834         struct ExpressMessage *newmsg;
835
836         if (CtdlAccessCheck(ac_aide)) return;
837         which_session = extract_int(argbuf, 0);
838
839         begin_critical_section(S_SESSION_TABLE);
840         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
841                 if ((ccptr->cs_pid == which_session) || (which_session == 0)) {
842
843                         newmsg = (struct ExpressMessage *)
844                                 malloc(sizeof (struct ExpressMessage));
845                         memset(newmsg, 0,
846                                 sizeof (struct ExpressMessage));
847                         time(&(newmsg->timestamp));
848                         safestrncpy(newmsg->sender, CC->user.fullname,
849                                     sizeof newmsg->sender);
850                         newmsg->flags |= EM_GO_AWAY;
851                         newmsg->text = strdup("Automatic logoff requested.");
852
853                         add_xmsg_to_context(ccptr, newmsg);
854                         ++sessions;
855
856                 }
857         }
858         end_critical_section(S_SESSION_TABLE);
859         cprintf("%d Sent termination request to %d sessions.\n", CIT_OK, sessions);
860 }
861
862
863 /*
864  * This is the back end for flush_conversations_to_disk()
865  * At this point we've isolated a single conversation (struct imlog)
866  * and are ready to write it to disk.
867  */
868 void flush_individual_conversation(struct imlog *im) {
869         struct CtdlMessage *msg;
870         long msgnum = 0;
871         char roomname[ROOMNAMELEN];
872
873         StrBufAppendBufPlain(im->conversation, HKEY(
874                 "</body>\r\n"
875                 "</html>\r\n"
876                 ), 0
877         );
878
879         msg = malloc(sizeof(struct CtdlMessage));
880         memset(msg, 0, sizeof(struct CtdlMessage));
881         msg->cm_magic = CTDLMESSAGE_MAGIC;
882         msg->cm_anon_type = MES_NORMAL;
883         msg->cm_format_type = FMT_RFC822;
884         if (!IsEmptyStr(im->usernames[0])) {
885                 msg->cm_fields['A'] = strdup(im->usernames[0]);
886         } else {
887                 msg->cm_fields['A'] = strdup("Citadel");
888         }
889         if (!IsEmptyStr(im->usernames[1])) {
890                 msg->cm_fields['R'] = strdup(im->usernames[1]);
891         }
892         msg->cm_fields['O'] = strdup(PAGELOGROOM);
893         msg->cm_fields['N'] = strdup(NODENAME);
894         msg->cm_fields['M'] = SmashStrBuf(&im->conversation);   /* we own this memory now */
895
896         /* Start with usernums[1] because it's guaranteed to be higher than usernums[0],
897          * so if there's only one party, usernums[0] will be zero but usernums[1] won't.
898          * Create the room if necessary.  Note that we create as a type 5 room rather
899          * than 4, which indicates that it's a personal room but we've already supplied
900          * the namespace prefix.
901          *
902          * In the unlikely event that usernums[1] is zero, a room with an invalid namespace
903          * prefix will be created.  That's ok because the auto-purger will clean it up later.
904          */
905         snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[1], PAGELOGROOM);
906         create_room(roomname, 5, "", 0, 1, 1, VIEW_BBS);
907         msgnum = CtdlSubmitMsg(msg, NULL, roomname, 0);
908         CtdlFreeMessage(msg);
909
910         /* If there is a valid user number in usernums[0], save a copy for them too. */
911         if (im->usernums[0] > 0) {
912                 snprintf(roomname, sizeof roomname, "%010ld.%s", im->usernums[0], PAGELOGROOM);
913                 create_room(roomname, 5, "", 0, 1, 1, VIEW_BBS);
914                 CtdlSaveMsgPointerInRoom(roomname, msgnum, 0, NULL);
915         }
916
917         /* Finally, if we're logging instant messages globally, do that now. */
918         if (!IsEmptyStr(config.c_logpages)) {
919                 create_room(config.c_logpages, 3, "", 0, 1, 1, VIEW_BBS);
920                 CtdlSaveMsgPointerInRoom(config.c_logpages, msgnum, 0, NULL);
921         }
922
923 }
924
925 /*
926  * Locate instant message conversations which have gone idle
927  * (or, if the server is shutting down, locate *all* conversations)
928  * and flush them to disk (in the participants' log rooms, etc.)
929  */
930 void flush_conversations_to_disk(time_t if_older_than) {
931
932         struct imlog *flush_these = NULL;
933         struct imlog *dont_flush_these = NULL;
934         struct imlog *imptr = NULL;
935
936         begin_critical_section(S_IM_LOGS);
937         while (imlist)
938         {
939                 imptr = imlist;
940                 imlist = imlist->next;
941                 if ((time(NULL) - imptr->lastmsg) > if_older_than)
942                 {
943                         /* This conversation qualifies.  Move it to the list of ones to flush. */
944                         imptr->next = flush_these;
945                         flush_these = imptr;
946                 }
947                 else  {
948                         /* Move it to the list of ones not to flush. */
949                         imptr->next = dont_flush_these;
950                         dont_flush_these = imptr;
951                 }
952         }
953         imlist = dont_flush_these;
954         end_critical_section(S_IM_LOGS);
955
956         /* We are now outside of the critical section, and we are the only thread holding a
957          * pointer to a linked list of conversations to be flushed to disk.
958          */
959         while (flush_these) {
960
961                 flush_individual_conversation(flush_these);     /* This will free the string buffer */
962                 imptr = flush_these;
963                 flush_these = flush_these->next;
964                 free(imptr);
965         }
966 }
967
968
969
970 void chat_timer(void) {
971         flush_conversations_to_disk(300);       /* Anything that hasn't peeped in more than 5 minutes */
972 }
973
974 void chat_shutdown(void) {
975         flush_conversations_to_disk(0);         /* Get it ALL onto disk NOW. */
976 }
977
978 CTDL_MODULE_INIT(chat)
979 {
980         if (!threading)
981         {
982                 CtdlRegisterProtoHook(cmd_chat, "CHAT", "Begin real-time chat");
983                 CtdlRegisterProtoHook(cmd_pexp, "PEXP", "Poll for instant messages");
984                 CtdlRegisterProtoHook(cmd_gexp, "GEXP", "Get instant messages");
985                 CtdlRegisterProtoHook(cmd_sexp, "SEXP", "Send an instant message");
986                 CtdlRegisterProtoHook(cmd_dexp, "DEXP", "Disable instant messages");
987                 CtdlRegisterProtoHook(cmd_reqt, "REQT", "Request client termination");
988                 CtdlRegisterSessionHook(cmd_gexp_async, EVT_ASYNC);
989                 CtdlRegisterSessionHook(delete_instant_messages, EVT_STOP);
990                 CtdlRegisterXmsgHook(send_instant_message, XMSG_PRI_LOCAL);
991                 CtdlRegisterSessionHook(chat_timer, EVT_TIMER);
992                 CtdlRegisterSessionHook(chat_shutdown, EVT_SHUTDOWN);
993         }
994         
995         /* return our Subversion id for the Log */
996         return "$Id$";
997 }