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