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