More removal of $Id$ tags
[citadel.git] / citadel / textclient / messages.c
1 /*
2  * Text client functions for reading and writing of messages
3  *
4  * Copyright (c) 1987-2010 by the citadel.org team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <limits.h>
32 #include <sys/wait.h>
33 #include <sys/stat.h>
34
35 #if TIME_WITH_SYS_TIME
36 # include <sys/time.h>
37 # include <time.h>
38 #else
39 # if HAVE_SYS_TIME_H
40 #  include <sys/time.h>
41 # else
42 #  include <time.h>
43 # endif
44 #endif
45
46 #ifdef HAVE_PTHREAD_H
47 #include <pthread.h>
48 #endif
49
50 #include <stdarg.h>
51 #include <libcitadel.h>
52 #include "citadel.h"
53 #include "citadel_ipc.h"
54 #include "citadel_decls.h"
55 #include "messages.h"
56 #include "commands.h"
57 #include "rooms.h"
58 #ifndef HAVE_SNPRINTF
59 #include "snprintf.h"
60 #endif
61 #include "screen.h"
62
63 #define MAXWORDBUF SIZ
64 #define NO_REPLY_TO     "nobody ... xxxxxx"
65
66 char reply_to[SIZ];
67 char reply_subject[SIZ];
68 char reply_references[SIZ];
69 char reply_inreplyto[SIZ];
70
71 struct cittext {
72         struct cittext *next;
73         char text[MAXWORDBUF];
74 };
75
76 void stty_ctdl(int cmd);
77 int haschar(const char *st, int ch);
78 void ctdl_getline(char *string, int lim);
79 int file_checksum(char *filename);
80 void progress(CtdlIPC* ipc, unsigned long curr, unsigned long cmax);
81
82 unsigned long *msg_arr = NULL;
83 int msg_arr_size = 0;
84 int num_msgs;
85 char rc_alt_semantics;
86 extern char room_name[];
87 extern char tempdir[];
88 extern unsigned room_flags;
89 extern unsigned room_flags2;
90 extern int entmsg_ok;
91 extern long highest_msg_read;
92 extern char temp[];
93 extern char temp2[];
94 extern int screenwidth;
95 extern int screenheight;
96 extern long maxmsgnum;
97 extern char is_mail;
98 extern char is_aide;
99 extern char is_room_aide;
100 extern char fullname[];
101 extern char axlevel;
102 extern unsigned userflags;
103 extern char sigcaught;
104 extern char printcmd[];
105 extern int rc_allow_attachments;
106 extern int rc_display_message_numbers;
107 extern int rc_force_mail_prompts;
108 extern int editor_pid;
109 extern CtdlIPC *ipc_for_signal_handlers;        /* KLUDGE cover your eyes */
110 int num_urls = 0;
111 char urls[MAXURLS][SIZ];
112 char imagecmd[SIZ];
113 int has_images = 0;                             /* Current msg has images */
114 struct parts *last_message_parts = NULL;        /* Parts from last msg */
115
116
117
118 void ka_sigcatch(int signum)
119 {
120         alarm(S_KEEPALIVE);
121         signal(SIGALRM, ka_sigcatch);
122         CtdlIPCNoop(ipc_for_signal_handlers);
123 }
124
125
126 /*
127  * server keep-alive version of wait() (needed for external editor)
128  */
129 pid_t ka_wait(int *kstatus)
130 {
131         pid_t p;
132
133         alarm(S_KEEPALIVE);
134         signal(SIGALRM, ka_sigcatch);
135         do {
136                 errno = 0;
137                 p = wait(kstatus);
138         } while (errno == EINTR);
139         signal(SIGALRM, SIG_IGN);
140         alarm(0);
141         return (p);
142 }
143
144
145 /*
146  * version of system() that uses ka_wait()
147  */
148 int ka_system(char *shc)
149 {
150         pid_t childpid;
151         pid_t waitpid;
152         int retcode;
153
154         childpid = fork();
155         if (childpid < 0) {
156                 color(BRIGHT_RED);
157                 perror("Cannot fork");
158                 color(DIM_WHITE);
159                 return ((pid_t) childpid);
160         }
161
162         if (childpid == 0) {
163                 execlp("/bin/sh", "sh", "-c", shc, NULL);
164                 exit(127);
165         }
166
167         if (childpid > 0) {
168                 do {
169                         waitpid = ka_wait(&retcode);
170                 } while (waitpid != childpid);
171                 return (retcode);
172         }
173
174         return (-1);
175 }
176
177
178
179 /*
180  * add a newline to the buffer...
181  */
182 void add_newline(struct cittext *textlist)
183 {
184         struct cittext *ptr;
185
186         ptr = textlist;
187         while (ptr->next != NULL)
188                 ptr = ptr->next;
189
190         while (ptr->text[strlen(ptr->text) - 1] == 32)
191                 ptr->text[strlen(ptr->text) - 1] = 0;
192         /* strcat(ptr->text,"\n"); */
193
194         ptr->next = (struct cittext *)
195             malloc(sizeof(struct cittext));
196         ptr = ptr->next;
197         ptr->next = NULL;
198         strcpy(ptr->text, "");
199 }
200
201
202 /*
203  * add a word to the buffer...
204  */
205 void add_word(struct cittext *textlist, char *wordbuf)
206 {
207         struct cittext *ptr;
208
209         ptr = textlist;
210         while (ptr->next != NULL)
211                 ptr = ptr->next;
212
213         if (3 + strlen(ptr->text) + strlen(wordbuf) > screenwidth) {
214                 ptr->next = (struct cittext *)
215                     malloc(sizeof(struct cittext));
216                 ptr = ptr->next;
217                 ptr->next = NULL;
218                 strcpy(ptr->text, "");
219         }
220
221         strcat(ptr->text, wordbuf);
222         strcat(ptr->text, " ");
223 }
224
225
226 /*
227  * begin editing of an opened file pointed to by fp
228  */
229 void citedit(FILE *fp)
230 {
231         int a, prev, finished, b, last_space;
232         int appending = 0;
233         struct cittext *textlist = NULL;
234         struct cittext *ptr;
235         char wordbuf[MAXWORDBUF];
236         int rv = 0;
237
238         /* first, load the text into the buffer */
239         fseek(fp, 0L, 0);
240         textlist = (struct cittext *) malloc(sizeof(struct cittext));
241         textlist->next = NULL;
242         strcpy(textlist->text, "");
243
244         strcpy(wordbuf, "");
245         prev = (-1);
246         while (a = getc(fp), a >= 0) {
247                 appending = 1;
248                 if ((a == 32) || (a == 9) || (a == 13) || (a == 10)) {
249                         add_word(textlist, wordbuf);
250                         strcpy(wordbuf, "");
251                         if ((prev == 13) || (prev == 10)) {
252                                 add_word(textlist, "\n");
253                                 add_newline(textlist);
254                                 add_word(textlist, "");
255                         }
256                 } else {
257                         wordbuf[strlen(wordbuf) + 1] = 0;
258                         wordbuf[strlen(wordbuf)] = a;
259                 }
260                 if (strlen(wordbuf) + 3 > screenwidth) {
261                         add_word(textlist, wordbuf);
262                         strcpy(wordbuf, "");
263                 }
264                 prev = a;
265         }
266
267         /* get text */
268         finished = 0;
269         prev = (appending ? 13 : (-1));
270         strcpy(wordbuf, "");
271         async_ka_start();
272         do {
273                 a = inkey();
274                 if (a == 10)
275                         a = 13;
276                 if (a == 9)
277                         a = 32;
278                 if (a == 127)
279                         a = 8;
280
281                 if ((a != 32) && (prev == 13)) {
282                         add_word(textlist, "\n");
283                         scr_printf(" ");
284                 }
285
286                 if ((a == 32) && (prev == 13)) {
287                         add_word(textlist, "\n");
288                         add_newline(textlist);
289                 }
290
291                 if (a == 8) {
292                         if (!IsEmptyStr(wordbuf)) {
293                                 wordbuf[strlen(wordbuf) - 1] = 0;
294                                 scr_putc(8);
295                                 scr_putc(32);
296                                 scr_putc(8);
297                         }
298                 } else if (a == 23) {
299                         do {
300                                 wordbuf[strlen(wordbuf) - 1] = 0;
301                                 scr_putc(8);
302                                 scr_putc(32);
303                                 scr_putc(8);
304                         } while (!IsEmptyStr(wordbuf) && wordbuf[strlen(wordbuf) - 1] != ' ');
305                 } else if (a == 13) {
306                         scr_printf("\n");
307                         if (IsEmptyStr(wordbuf))
308                                 finished = 1;
309                         else {
310                                 for (b = 0; b < strlen(wordbuf); ++b)
311                                         if (wordbuf[b] == 32) {
312                                                 wordbuf[b] = 0;
313                                                 add_word(textlist,
314                                                          wordbuf);
315                                                 strcpy(wordbuf,
316                                                        &wordbuf[b + 1]);
317                                                 b = 0;
318                                         }
319                                 add_word(textlist, wordbuf);
320                                 strcpy(wordbuf, "");
321                         }
322                 } else {
323                         scr_putc(a);
324                         wordbuf[strlen(wordbuf) + 1] = 0;
325                         wordbuf[strlen(wordbuf)] = a;
326                 }
327                 if ((strlen(wordbuf) + 3) > screenwidth) {
328                         last_space = (-1);
329                         for (b = 0; b < strlen(wordbuf); ++b)
330                                 if (wordbuf[b] == 32)
331                                         last_space = b;
332                         if (last_space >= 0) {
333                                 for (b = 0; b < strlen(wordbuf); ++b)
334                                         if (wordbuf[b] == 32) {
335                                                 wordbuf[b] = 0;
336                                                 add_word(textlist,
337                                                          wordbuf);
338                                                 strcpy(wordbuf,
339                                                        &wordbuf[b + 1]);
340                                                 b = 0;
341                                         }
342                                 for (b = 0; b < strlen(wordbuf); ++b) {
343                                         scr_putc(8);
344                                         scr_putc(32);
345                                         scr_putc(8);
346                                 }
347                                 scr_printf("\n%s", wordbuf);
348                         } else {
349                                 add_word(textlist, wordbuf);
350                                 strcpy(wordbuf, "");
351                                 scr_printf("\n");
352                         }
353                 }
354                 prev = a;
355         } while (finished == 0);
356         async_ka_end();
357
358         /* write the buffer back to disk */
359         fseek(fp, 0L, 0);
360         for (ptr = textlist; ptr != NULL; ptr = ptr->next) {
361                 fprintf(fp, "%s", ptr->text);
362         }
363         putc(10, fp);
364         fflush(fp);
365         rv = ftruncate(fileno(fp), ftell(fp));
366
367         /* and deallocate the memory we used */
368         while (textlist != NULL) {
369                 ptr = textlist->next;
370                 free(textlist);
371                 textlist = ptr;
372         }
373 }
374
375
376 /*
377  * Free the struct parts
378  */
379 void free_parts(struct parts *p)
380 {
381         struct parts *a_part = p;
382
383         while (a_part) {
384                 struct parts *q;
385
386                 q = a_part;
387                 a_part = a_part->next;
388                 free(q);
389         }
390 }
391
392
393 /*
394  * Read a message from the server
395  */
396 int read_message(CtdlIPC *ipc,
397         long num,   /* message number */
398         int pagin, /* 0 = normal read, 1 = read with pagination, 2 = header */
399         FILE *dest) /* Destination file, NULL for screen */
400 {
401         char buf[SIZ];
402         char now[SIZ];
403         int format_type = 0;
404         int fr = 0;
405         int nhdr = 0;
406         struct ctdlipcmessage *message = NULL;
407         int r;                          /* IPC response code */
408         char *converted_text = NULL;
409         char *lineptr;
410         char *nextline;
411         char *searchptr;
412         int i;
413         char ch;
414         int linelen;
415         int final_line_is_blank = 0;
416
417         has_images = 0;
418
419         sigcaught = 0;
420         stty_ctdl(1);
421
422         strcpy(reply_to, NO_REPLY_TO);
423         strcpy(reply_subject, "");
424         strcpy(reply_references, "");
425         strcpy(reply_inreplyto, "");
426
427         r = CtdlIPCGetSingleMessage(ipc, num, (pagin == READ_HEADER ? 1 : 0), 4, &message, buf);
428         if (r / 100 != 1) {
429                 err_printf("*** msg #%ld: %d %s\n", num, r, buf);
430                 ++lines_printed;
431                 lines_printed = checkpagin(lines_printed, pagin, screenheight);
432                 stty_ctdl(0);
433                 free(message->text);
434                 free_parts(message->attachments);
435                 free(message);
436                 return (0);
437         }
438
439         if (dest) {
440                 fprintf(dest, "\n ");
441         } else {
442                 scr_printf("\n");
443                 ++lines_printed;
444                 lines_printed = checkpagin(lines_printed, pagin, screenheight);
445                 if (pagin != 2)
446                         scr_printf(" ");
447         }
448         if (pagin == 1 && !dest) {
449                 color(BRIGHT_CYAN);
450         }
451
452         /* View headers only */
453         if (pagin == 2) {
454                 pprintf("nhdr=%s\nfrom=%s\ntype=%d\nmsgn=%s\n",
455                                 message->nhdr ? "yes" : "no",
456                                 message->author, message->type,
457                                 message->msgid);
458                 if (!IsEmptyStr(message->subject)) {
459                         pprintf("subj=%s\n", message->subject);
460                 }
461                 if (!IsEmptyStr(message->email)) {
462                         pprintf("rfca=%s\n", message->email);
463                 }
464                 pprintf("hnod=%s\nroom=%s\nnode=%s\ntime=%s",
465                                 message->hnod, message->room,
466                                 message->node, 
467                                 asctime(localtime(&message->time)));
468                 if (!IsEmptyStr(message->recipient)) {
469                         pprintf("rcpt=%s\n", message->recipient);
470                 }
471                 if (message->attachments) {
472                         struct parts *ptr;
473
474                         for (ptr = message->attachments; ptr; ptr = ptr->next) {
475                                 pprintf("part=%s|%s|%s|%s|%s|%ld\n",
476                                         ptr->name, ptr->filename, ptr->number,
477                                         ptr->disposition, ptr->mimetype,
478                                         ptr->length);
479                         }
480                 }
481                 pprintf("\n");
482                 stty_ctdl(0);
483                 free(message->text);
484                 free_parts(message->attachments);
485                 free(message);
486                 return (0);
487         }
488
489         if (rc_display_message_numbers) {
490                 if (dest) {
491                         fprintf(dest, "[#%s] ", message->msgid);
492                 } else {
493                         color(DIM_WHITE);
494                         scr_printf("[");
495                         color(BRIGHT_WHITE);
496                         scr_printf("#%s", message->msgid);
497                         color(DIM_WHITE);
498                         scr_printf("] ");
499                 }
500         }
501         if (nhdr == 1 && !is_room_aide) {
502                 if (dest) {
503                         fprintf(dest, " ****");
504                 } else {
505                         scr_printf(" ****");
506                 }
507         } else {
508                 fmt_date(now, sizeof now, message->time, 0);
509                 if (dest) {
510                         fprintf(dest, "%s from %s ", now, message->author);
511                         if (!IsEmptyStr(message->email)) {
512                                 fprintf(dest, "<%s> ", message->email);
513                         }
514                 } else {
515                         color(BRIGHT_CYAN);
516                         scr_printf("%s ", now);
517                         color(DIM_WHITE);
518                         scr_printf("from ");
519                         color(BRIGHT_CYAN);
520                         scr_printf("%s ", message->author);
521                         if (!IsEmptyStr(message->email)) {
522                                 color(DIM_WHITE);
523                                 scr_printf("<");
524                                 color(BRIGHT_BLUE);
525                                 scr_printf("%s", message->email);
526                                         color(DIM_WHITE);
527                                 scr_printf("> ");
528                         }
529                 }
530                 if (!IsEmptyStr(message->node)) {
531                         if ((room_flags & QR_NETWORK)
532                             || ((strcasecmp(message->node, ipc->ServInfo.nodename)
533                              && (strcasecmp(message->node, ipc->ServInfo.fqdn))))) {
534                                 if (IsEmptyStr(message->email)) {
535                                         if (dest) {
536                                                 fprintf(dest, "@%s ", message->node);
537                                         } else {
538                                                 color(DIM_WHITE);
539                                                 scr_printf("@");
540                                                 color(BRIGHT_YELLOW);
541                                                 scr_printf("%s ", message->node);
542                                         }
543                                 }
544                         }
545                 }
546                 if (strcasecmp(message->hnod, ipc->ServInfo.humannode)
547                     && (!IsEmptyStr(message->hnod)) && (IsEmptyStr(message->email))) {
548                         if (dest) {
549                                 fprintf(dest, "(%s) ", message->hnod);
550                         } else {
551                                 color(DIM_WHITE);
552                                 scr_printf("(");
553                                 color(BRIGHT_WHITE);
554                                 scr_printf("%s", message->hnod);
555                                 color(DIM_WHITE);
556                                 scr_printf(") ");
557                         }
558                 }
559                 if (strcasecmp(message->room, room_name) && (IsEmptyStr(message->email))) {
560                         if (dest) {
561                                 fprintf(dest, "in %s> ", message->room);
562                         } else {
563                                 color(DIM_WHITE);
564                                 scr_printf("in ");
565                                 color(BRIGHT_MAGENTA);
566                                 scr_printf("%s> ", message->room);
567                         }
568                 }
569                 if (!IsEmptyStr(message->recipient)) {
570                         if (dest) {
571                                 fprintf(dest, "to %s ", message->recipient);
572                         } else {
573                                 color(DIM_WHITE);
574                                 scr_printf("to ");
575                                 color(BRIGHT_CYAN);
576                                 scr_printf("%s ", message->recipient);
577                         }
578                 }
579         }
580         
581         if (dest) {
582                 fprintf(dest, "\n");
583         } else {
584                 scr_printf("\n");
585         }
586
587         /* Set the reply-to address to an Internet e-mail address if possible
588          */
589         if ((message->email != NULL) && (!IsEmptyStr(message->email))) {
590                 if (!IsEmptyStr(message->author)) {
591                         snprintf(reply_to, sizeof reply_to, "%s <%s>", message->author, message->email);
592                 }
593                 else {
594                         safestrncpy(reply_to, message->email, sizeof reply_to);
595                 }
596         }
597
598         /* But if we can't do that, set it to a Citadel address.
599          */
600         if (!strcmp(reply_to, NO_REPLY_TO)) {
601                 snprintf(reply_to, sizeof(reply_to), "%s @ %s",
602                          message->author, message->node);
603         }
604
605         if (!dest) {
606                 ++lines_printed;
607                 lines_printed = checkpagin(lines_printed, pagin, screenheight);
608         }
609
610
611         if (message->msgid != NULL) {
612                 safestrncpy(reply_inreplyto, message->msgid, sizeof reply_inreplyto);
613         }
614
615         if (message->references != NULL) if (!IsEmptyStr(message->references)) {
616                 safestrncpy(reply_references, message->references, sizeof reply_references);
617         }
618
619         if (message->subject != NULL) {
620                 safestrncpy(reply_subject, message->subject, sizeof reply_subject);
621                 if (!IsEmptyStr(message->subject)) {
622                         if (dest) {
623                                 fprintf(dest, "Subject: %s\n",
624                                                         message->subject);
625                         } else {
626                                 color(DIM_WHITE);
627                                 scr_printf("Subject: ");
628                                 color(BRIGHT_CYAN);
629                                 scr_printf("%s\n", message->subject);
630                                 ++lines_printed;
631                                 lines_printed = checkpagin(lines_printed,
632                                                 pagin, screenheight);
633                         }
634                 }
635         }
636
637         if (pagin == 1 && !dest) {
638                 color(BRIGHT_WHITE);
639         }
640
641         /******* end of header output, start of message text output *******/
642
643         /*
644          * Convert HTML to plain text, formatting for the actual width
645          * of the client screen.
646          */
647         if (!strcasecmp(message->content_type, "text/html")) {
648                 converted_text = html_to_ascii(message->text, 0, screenwidth, 0);
649                 if (converted_text != NULL) {
650                         free(message->text);
651                         message->text = converted_text;
652                         format_type = 1;
653                 }
654         }
655
656         /* Text/plain is a different type */
657         if (!strcasecmp(message->content_type, "text/plain")) {
658                 format_type = 1;
659         }
660
661         /* Extract URL's */
662         num_urls = 0;   /* Start with a clean slate */
663         searchptr = message->text;
664         while ( (searchptr != NULL) && (num_urls < MAXURLS) ) {
665                 searchptr = strstr(searchptr, "http://");
666                 if (searchptr != NULL) {
667                         safestrncpy(urls[num_urls], searchptr, sizeof(urls[num_urls]));
668                         for (i = 0; i < strlen(urls[num_urls]); i++) {
669                                 ch = urls[num_urls][i];
670                                 if (ch == '>' || ch == '\"' || ch == ')' ||
671                                     ch == ' ' || ch == '\n') {
672                                         urls[num_urls][i] = 0;
673                                         break;
674                                 }
675                         }
676                         num_urls++;
677                         ++searchptr;
678                 }
679         }
680
681         /*
682          * Here we go
683          */
684         if (format_type == 0) {
685                 fr = fmout(screenwidth, NULL, message->text, dest,
686                            ((pagin == 1) ? 1 : 0), screenheight, (-1), 1);
687         } else {
688                 /* renderer for text/plain */
689
690                 lineptr = message->text;
691
692                 do {
693                         nextline = strchr(lineptr, '\n');
694                         if (nextline != NULL) {
695                                 *nextline = 0;
696                                 ++nextline;
697                                 if (*nextline == 0) nextline = NULL;
698                         }
699
700                         if (sigcaught == 0) {
701                                 linelen = strlen(lineptr);
702                                 if (linelen && (lineptr[linelen-1] == '\r')) {
703                                         lineptr[--linelen] = 0;
704                                 }
705                                 if (dest) {
706                                         fprintf(dest, "%s\n", lineptr);
707                                 } else {
708                                         scr_printf("%s\n", lineptr);
709                                         lines_printed = lines_printed + 1 +
710                                             (linelen / screenwidth);
711                                         lines_printed =
712                                             checkpagin(lines_printed, pagin,
713                                                        screenheight);
714                                 }
715                         }
716                         if (lineptr[0] == 0) final_line_is_blank = 1;
717                         else final_line_is_blank = 0;
718                         lineptr = nextline;
719                 } while (nextline);
720                 fr = sigcaught;
721         }
722         if (!final_line_is_blank) {
723                 if (dest) {
724                         fprintf(dest, "\n");
725                 }
726                 else {
727                         scr_printf("\n");
728                         ++lines_printed;
729                         lines_printed = checkpagin(lines_printed, pagin, screenheight);
730                         fr = sigcaught;         
731                 }
732         }
733
734         /* Enumerate any attachments */
735         if ( (pagin == 1) && (message->attachments) ) {
736                 struct parts *ptr;
737
738                 for (ptr = message->attachments; ptr; ptr = ptr->next) {
739                         if ( (!strcasecmp(ptr->disposition, "attachment"))
740                            || (!strcasecmp(ptr->disposition, "inline"))
741                            || (!strcasecmp(ptr->disposition, ""))
742                         ) {
743                                 if ( (strcasecmp(ptr->number, message->mime_chosen))
744                                    && (!IsEmptyStr(ptr->mimetype))
745                                 ) {
746                                         color(DIM_WHITE);
747                                         pprintf("Part ");
748                                         color(BRIGHT_MAGENTA);
749                                         pprintf("%s", ptr->number);
750                                         color(DIM_WHITE);
751                                         pprintf(": ");
752                                         color(BRIGHT_CYAN);
753                                         pprintf("%s", ptr->filename);
754                                         color(DIM_WHITE);
755                                         pprintf(" (%s, %ld bytes)\n", ptr->mimetype, ptr->length);
756                                         if (!strncmp(ptr->mimetype, "image/", 6)) {
757                                                 has_images++;
758                                         }
759                                 }
760                         }
761                 }
762         }
763
764         /* Save the attachments info for later */
765         last_message_parts = message->attachments;
766
767         /* Now we're done */
768         free(message->text);
769         free(message);
770
771         if (pagin == 1 && !dest)
772                 color(DIM_WHITE);
773         stty_ctdl(0);
774         return (fr);
775 }
776
777 /*
778  * replace string function for the built-in editor
779  */
780 void replace_string(char *filename, long int startpos)
781 {
782         char buf[512];
783         char srch_str[128];
784         char rplc_str[128];
785         FILE *fp;
786         int a;
787         long rpos, wpos;
788         char *ptr;
789         int substitutions = 0;
790         long msglen = 0L;
791         int rv;
792
793         scr_printf("Enter text to be replaced:\n: ");
794         ctdl_getline(srch_str, (sizeof(srch_str)-1) );
795         if (IsEmptyStr(srch_str)) {
796                 return;
797         }
798
799         scr_printf("Enter text to replace it with:\n: ");
800         ctdl_getline(rplc_str, (sizeof(rplc_str)-1) );
801
802         fp = fopen(filename, "r+");
803         if (fp == NULL) {
804                 return;
805         }
806
807         wpos = startpos;
808         fseek(fp, startpos, 0);
809         strcpy(buf, "");
810         while (a = getc(fp), a > 0) {
811                 ++msglen;
812                 buf[strlen(buf) + 1] = 0;
813                 buf[strlen(buf)] = a;
814                 if (strlen(buf) >= strlen(srch_str)) {
815                         ptr = (&buf[strlen(buf) - strlen(srch_str)]);
816                         if (!strncmp(ptr, srch_str, strlen(srch_str))) {
817                                 strcpy(ptr, rplc_str);
818                                 ++substitutions;
819                         }
820                 }
821                 if (strlen(buf) > 384) {
822                         rpos = ftell(fp);
823                         fseek(fp, wpos, 0);
824                         rv = fwrite((char *) buf, 128, 1, fp);
825                         strcpy(buf, &buf[128]);
826                         wpos = ftell(fp);
827                         fseek(fp, rpos, 0);
828                 }
829         }
830         fseek(fp, wpos, 0);
831         if (!IsEmptyStr(buf)) {
832                 rv = fwrite((char *) buf, strlen(buf), 1, fp);
833         }
834         wpos = ftell(fp);
835         fclose(fp);
836         rv = truncate(filename, wpos);
837         scr_printf("<R>eplace made %d substitution(s).\n\n", substitutions);
838 }
839
840 /*
841  * Function to begin composing a new message
842  */
843 int client_make_message(CtdlIPC *ipc,
844                         char *filename,         /* temporary file name */
845                         char *recipient,        /* NULL if it's not mail */
846                         int is_anonymous,
847                         int format_type,
848                         int mode,
849                         char *subject,          /* buffer to store subject line */
850                         int subject_required
851 ) {
852         FILE *fp;
853         int a, b, e_ex_code;
854         long beg;
855         char datestr[SIZ];
856         char header[SIZ];
857         char *editor_path = NULL;
858         int cksum = 0;
859
860         if (mode >= 2)
861         {
862                 if ((mode-2) < MAX_EDITORS && !IsEmptyStr(editor_paths[mode-2]))
863                 {
864                         editor_path = editor_paths[mode-2];
865                 } else if (!IsEmptyStr(editor_paths[0]))
866                 {
867                         editor_path = editor_paths[0];
868                 } else {
869                         err_printf("*** No editor available; using built-in editor.\n");
870                         mode = 0;
871                 }
872         }
873
874         fmt_date(datestr, sizeof datestr, time(NULL), 0);
875         header[0] = 0;
876
877         if (room_flags & QR_ANONONLY && !recipient) {
878                 snprintf(header, sizeof header, " ****");
879         }
880         else {
881                 snprintf(header, sizeof header,
882                         " %s from %s",
883                         datestr,
884                         (is_anonymous ? "[anonymous]" : fullname)
885                         );
886                 if (!IsEmptyStr(recipient)) {
887                         size_t tmp = strlen(header);
888                         snprintf(&header[tmp], sizeof header - tmp,
889                                 " to %s", recipient);
890                 }
891         }
892         scr_printf("%s\n", header);
893         if (subject != NULL) if (!IsEmptyStr(subject)) {
894                 scr_printf("Subject: %s\n", subject);
895         }
896         
897         if ( (subject_required) && (IsEmptyStr(subject)) ) {
898                 newprompt("Subject: ", subject, 70);
899         }
900
901         beg = 0L;
902
903         if (mode == 1) {
904                 scr_printf("(Press ctrl-d when finished)\n");
905         }
906
907         if (mode == 0) {
908                 fp = fopen(filename, "r");
909                 if (fp != NULL) {
910                         fmout(screenwidth, fp, NULL, NULL, 0,
911                                 screenheight, 0, 0);
912                         beg = ftell(fp);
913                         fclose(fp);
914                 } else {
915                         fp = fopen(filename, "w");
916                         if (fp == NULL) {
917                                 err_printf("*** Error opening temp file!\n    %s: %s\n",
918                                         filename, strerror(errno)
919                                 );
920                         return(1);
921                         }
922                         fclose(fp);
923                 }
924         }
925
926 ME1:    switch (mode) {
927
928         case 0:
929                 fp = fopen(filename, "r+");
930                 if (fp == NULL) {
931                         err_printf("*** Error opening temp file!\n    %s: %s\n",
932                                 filename, strerror(errno)
933                         );
934                         return(1);
935                 }
936                 citedit(fp);
937                 fclose(fp);
938                 goto MECR;
939
940         case 1:
941                 fp = fopen(filename, "a");
942                 if (fp == NULL) {
943                         err_printf("*** Error opening temp file!\n"
944                                 "    %s: %s\n",
945                                 filename, strerror(errno));
946                         return(1);
947                 }
948                 do {
949                         a = inkey();
950                         if (a == 255)
951                                 a = 32;
952                         if (a == 13)
953                                 a = 10;
954                         if (a != 4) {
955                                 putc(a, fp);
956                                 scr_putc(a);
957                         }
958                         if (a == 10)
959                                 scr_putc(10);
960                 } while (a != 4);
961                 fclose(fp);
962                 break;
963
964         case 2:
965         default:        /* allow 2+ modes */
966                 e_ex_code = 1;  /* start with a failed exit code */
967                 screen_reset();
968                 stty_ctdl(SB_RESTORE);
969                 editor_pid = fork();
970                 cksum = file_checksum(filename);
971                 if (editor_pid == 0) {
972                         char tmp[SIZ];
973
974                         chmod(filename, 0600);
975                         snprintf(tmp, sizeof tmp, "WINDOW_TITLE=%s", header);
976                         putenv(tmp);
977                         execlp(editor_path, editor_path, filename, NULL);
978                         exit(1);
979                 }
980                 if (editor_pid > 0)
981                         do {
982                                 e_ex_code = 0;
983                                 b = ka_wait(&e_ex_code);
984                         } while ((b != editor_pid) && (b >= 0));
985                 editor_pid = (-1);
986                 stty_ctdl(0);
987                 screen_set();
988                 break;
989         }
990
991 MECR:   if (mode >= 2) {
992                 if (file_checksum(filename) == cksum) {
993                         err_printf("*** Aborted message.\n");
994                         e_ex_code = 1;
995                 }
996                 if (e_ex_code == 0) {
997                         goto MEFIN;
998                 }
999                 goto MEABT2;
1000         }
1001
1002         b = keymenu("Entry command (? for options)",
1003                 "<A>bort|"
1004                 "<C>ontinue|"
1005                 "<S>ave message|"
1006                 "<P>rint formatted|"
1007                 "add s<U>bject|"
1008                 "<R>eplace string|"
1009                 "<H>old message"
1010         );
1011
1012         if (b == 'a') goto MEABT;
1013         if (b == 'c') goto ME1;
1014         if (b == 's') goto MEFIN;
1015         if (b == 'p') {
1016                 scr_printf(" %s from %s", datestr, fullname);
1017                 if (!IsEmptyStr(recipient)) {
1018                         scr_printf(" to %s", recipient);
1019                 }
1020                 scr_printf("\n");
1021                 if (subject != NULL) if (!IsEmptyStr(subject)) {
1022                         scr_printf("Subject: %s\n", subject);
1023                 }
1024                 fp = fopen(filename, "r");
1025                 if (fp != NULL) {
1026                         fmout(screenwidth, fp, NULL, NULL,
1027                               ((userflags & US_PAGINATOR) ? 1 : 0),
1028                               screenheight, 0, 0);
1029                         beg = ftell(fp);
1030                         fclose(fp);
1031                 }
1032                 goto MECR;
1033         }
1034         if (b == 'r') {
1035                 replace_string(filename, 0L);
1036                 goto MECR;
1037         }
1038         if (b == 'h') {
1039                 return (2);
1040         }
1041         if (b == 'u') {
1042                 if (subject != NULL) {
1043                         newprompt("Subject: ", subject, 70);
1044                 }
1045                 goto MECR;
1046         }
1047
1048 MEFIN:  return (0);
1049
1050 MEABT:  scr_printf("Are you sure? ");
1051         if (yesno() == 0) {
1052                 goto ME1;
1053         }
1054 MEABT2: unlink(filename);
1055         return (2);
1056 }
1057
1058
1059 /*
1060  * Make sure there's room in msg_arr[] for at least one more.
1061  */
1062 void check_msg_arr_size(void) {
1063         if ((num_msgs + 1) > msg_arr_size) {
1064                 msg_arr_size += 512;
1065                 msg_arr = realloc(msg_arr,
1066                         ((sizeof(long)) * msg_arr_size) );
1067         }
1068 }
1069
1070
1071 /*
1072  * break_big_lines()  -  break up lines that are >1024 characters
1073  *                       otherwise the server will truncate
1074  */
1075 void break_big_lines(char *msg) {
1076         char *ptr;
1077         char *break_here;
1078
1079         if (msg == NULL) {
1080                 return;
1081         }
1082
1083         ptr = msg;
1084         while (strlen(ptr) > 1000) {
1085                 break_here = strchr(&ptr[900], ' ');
1086                 if ((break_here == NULL) || (break_here > &ptr[999])) {
1087                         break_here = &ptr[999];
1088                 }
1089                 *break_here = '\n';
1090                 ptr = break_here++;
1091         }
1092 }
1093
1094
1095 /*
1096  * entmsg()  -  edit and create a message
1097  *              returns 0 if message was saved
1098  */
1099 int entmsg(CtdlIPC *ipc,
1100                 int is_reply,   /* nonzero if this was a <R>eply command */
1101                 int c,          /* mode */
1102                 int masquerade  /* prompt for a non-default display name? */
1103 ) {
1104         char buf[SIZ];
1105         int a, b;
1106         int need_recp = 0;
1107         int mode;
1108         long highmsg = 0L;
1109         FILE *fp;
1110         char subject[SIZ];
1111         struct ctdlipcmessage message;
1112         unsigned long *msgarr = NULL;
1113         int r;                  /* IPC response code */
1114         int subject_required = 0;
1115
1116         if (!entmsg_ok) {
1117                 scr_printf("You may not enter messages in this type of room.\n");
1118                 return(1);
1119         }
1120
1121         if (c > 0) {
1122                 mode = 1;
1123         }
1124         else {
1125                 mode = 0;
1126         }
1127
1128         strcpy(subject, "");
1129
1130         /*
1131          * First, check to see if we have permission to enter a message in
1132          * this room.  The server will return an error code if we can't.
1133          */
1134         strcpy(message.recipient, "");
1135         strcpy(message.author, "");
1136         strcpy(message.subject, "");
1137         strcpy(message.references, "");
1138         message.text = "";              /* point to "", changes later */
1139         message.anonymous = 0;
1140         message.type = mode;
1141
1142         if (masquerade) {
1143                 newprompt("Display name for this message: ", message.author, 40);
1144         }
1145
1146         r = CtdlIPCPostMessage(ipc, 0, &subject_required, &message, buf);
1147
1148         if (r / 100 != 2 && r / 10 != 57) {
1149                 scr_printf("%s\n", buf);
1150                 return (1);
1151         }
1152
1153         /* Error code 570 is special.  It means that we CAN enter a message
1154          * in this room, but a recipient needs to be specified.
1155          */
1156         need_recp = 0;
1157         if (r / 10 == 57) {
1158                 need_recp = 1;
1159         }
1160
1161         /* If the user is a dumbass, tell them how to type. */
1162         if ((userflags & US_EXPERT) == 0) {
1163                 formout(ipc, "entermsg");
1164         }
1165
1166         /* Handle the selection of a recipient, if necessary. */
1167         strcpy(buf, "");
1168         if (need_recp == 1) {
1169                 if (axlevel >= AxProbU) {
1170                         if (is_reply) {
1171                                 strcpy(buf, reply_to);
1172                         } else {
1173                                 scr_printf("Enter recipient: ");
1174                                 ctdl_getline(buf, (SIZ-100) );
1175                                 if (IsEmptyStr(buf))
1176                                         return (1);
1177                         }
1178                 } else
1179                         strcpy(buf, "sysop");
1180         }
1181         strcpy(message.recipient, buf);
1182
1183         if (is_reply) {
1184
1185                 if (!IsEmptyStr(reply_subject)) {
1186                         if (!strncasecmp(reply_subject,
1187                            "Re: ", 3)) {
1188                                 strcpy(message.subject, reply_subject);
1189                         }
1190                         else {
1191                                 snprintf(message.subject,
1192                                         sizeof message.subject,
1193                                         "Re: %s",
1194                                         reply_subject);
1195                         }
1196                 }
1197
1198                 /* Trim down excessively long lists of thread references.  We eliminate the
1199                  * second one in the list so that the thread root remains intact.
1200                  */
1201                 int rrtok = num_tokens(reply_references, '|');
1202                 int rrlen = strlen(reply_references);
1203                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1204                         remove_token(reply_references, 1, '|');
1205                 }
1206
1207                 snprintf(message.references, sizeof message.references, "%s%s%s",
1208                         reply_references,
1209                         (IsEmptyStr(reply_references) ? "" : "|"),
1210                         reply_inreplyto
1211                 );
1212         }
1213
1214         if (room_flags & QR_ANONOPT) {
1215                 scr_printf("Anonymous (Y/N)? ");
1216                 if (yesno() == 1)
1217                         message.anonymous = 1;
1218         }
1219
1220         /* If it's mail, we've got to check the validity of the recipient... */
1221         if (!IsEmptyStr(message.recipient)) {
1222                 r = CtdlIPCPostMessage(ipc, 0, &subject_required,  &message, buf);
1223                 if (r / 100 != 2) {
1224                         scr_printf("%s\n", buf);
1225                         return (1);
1226                 }
1227         }
1228
1229         /* Learn the number of the newest message in in the room, so we can
1230          * tell upon saving whether someone else has posted too.
1231          */
1232         num_msgs = 0;
1233         r = CtdlIPCGetMessages(ipc, LastMessages, 1, NULL, &msgarr, buf);
1234         if (r / 100 != 1) {
1235                 scr_printf("%s\n", buf);
1236         } else {
1237                 for (num_msgs = 0; msgarr[num_msgs]; num_msgs++)
1238                         ;
1239         }
1240
1241         /* Now compose the message... */
1242         if (client_make_message(ipc, temp, message.recipient,
1243            message.anonymous, 0, c, message.subject, subject_required) != 0) {
1244             if (msgarr) free(msgarr);   
1245                 return (2);
1246         }
1247
1248         /* Reopen the temp file that was created, so we can send it */
1249         fp = fopen(temp, "r");
1250
1251         if (!fp || !(message.text = load_message_from_file(fp))) {
1252                 err_printf("*** Internal error while trying to save message!\n"
1253                         "%s: %s\n",
1254                         temp, strerror(errno));
1255                 unlink(temp);
1256                 return(errno);
1257         }
1258
1259         if (fp) fclose(fp);
1260
1261         /* Break lines that are >1024 characters, otherwise the server
1262          * will truncate them.
1263          */
1264         break_big_lines(message.text);
1265
1266         /* Transmit message to the server */
1267         r = CtdlIPCPostMessage(ipc, 1, NULL, &message, buf);
1268         if (r / 100 != 4) {
1269                 scr_printf("%s\n", buf);
1270                 return (1);
1271         }
1272
1273         /* Yes, unlink it now, so it doesn't stick around if we crash */
1274         unlink(temp);
1275
1276         if (num_msgs >= 1) highmsg = msgarr[num_msgs - 1];
1277
1278         if (msgarr) free(msgarr);
1279         msgarr = NULL;
1280         r = CtdlIPCGetMessages(ipc, NewMessages, 0, NULL, &msgarr, buf);
1281         if (r / 100 != 1) {
1282                 scr_printf("%s\n", buf);
1283         } else {
1284                 for (num_msgs = 0; msgarr[num_msgs]; num_msgs++)
1285                         ;
1286         }
1287
1288         /* get new highest message number in room to set lrp for goto... */
1289         maxmsgnum = msgarr[num_msgs - 1];
1290
1291         /* now see if anyone else has posted in here */
1292         b = (-1);
1293         for (a = 0; a < num_msgs; ++a) {
1294                 if (msgarr[a] > highmsg) {
1295                         ++b;
1296                 }
1297         }
1298         if (msgarr) free(msgarr);
1299         msgarr = NULL;
1300
1301         /* In the Mail> room, this algorithm always counts one message
1302          * higher than in public rooms, so we decrement it by one.
1303          */
1304         if (need_recp) {
1305                 --b;
1306         }
1307
1308         if (b == 1) {
1309                 scr_printf("*** 1 additional message has been entered "
1310                         "in this room by another user.\n");
1311         }
1312         else if (b > 1) {
1313                 scr_printf("*** %d additional messages have been entered "
1314                         "in this room by other users.\n", b);
1315         }
1316     free(message.text);
1317
1318         return(0);
1319 }
1320
1321 /*
1322  * Do editing on a quoted file
1323  */
1324 void process_quote(void)
1325 {
1326         FILE *qfile, *tfile;
1327         char buf[128];
1328         int line, qstart, qend;
1329
1330         /* Unlink the second temp file as soon as it's opened, so it'll get
1331          * deleted even if the program dies
1332          */
1333         qfile = fopen(temp2, "r");
1334         unlink(temp2);
1335
1336         /* Display the quotable text with line numbers added */
1337         line = 0;
1338         if (fgets(buf, 128, qfile) == NULL) {
1339                 /* we're skipping a line here */
1340         }
1341         while (fgets(buf, 128, qfile) != NULL) {
1342                 scr_printf("%3d %s", ++line, buf);
1343         }
1344         scr_printf("Begin quoting at [1] : ");
1345         ctdl_getline(buf, 4);
1346         qstart = (buf[0] == 0) ? (1) : atoi(buf);
1347         scr_printf("  End quoting at [%d] : ", line);
1348         ctdl_getline(buf, 4);
1349         qend = (buf[0] == 0) ? (line) : atoi(buf);
1350         rewind(qfile);
1351         line = 0;
1352         if (fgets(buf, 128, qfile) == NULL) {
1353                 /* we're skipping a line here */
1354         }
1355         tfile = fopen(temp, "w");
1356         while (fgets(buf, 128, qfile) != NULL) {
1357                 if ((++line >= qstart) && (line <= qend))
1358                         fprintf(tfile, " >%s", buf);
1359         }
1360         fprintf(tfile, " \n");
1361         fclose(qfile);
1362         fclose(tfile);
1363         chmod(temp, 0666);
1364 }
1365
1366
1367
1368 /*
1369  * List the URL's which were embedded in the previous message
1370  */
1371 void list_urls(CtdlIPC *ipc)
1372 {
1373         int i;
1374         char cmd[SIZ];
1375         int rv;
1376
1377         if (num_urls == 0) {
1378                 scr_printf("There were no URL's in the previous message.\n\n");
1379                 return;
1380         }
1381
1382         for (i = 0; i < num_urls; ++i) {
1383                 scr_printf("%3d %s\n", i + 1, urls[i]);
1384         }
1385
1386         if ((i = num_urls) != 1)
1387                 i = intprompt("Display which one", 1, 1, num_urls);
1388
1389         snprintf(cmd, sizeof cmd, rc_url_cmd, urls[i - 1]);
1390         rv = system(cmd);
1391         scr_printf("\n");
1392 }
1393
1394
1395 /*
1396  * Run image viewer in background
1397  */
1398 int do_image_view(const char *filename)
1399 {
1400         char cmd[SIZ];
1401         pid_t childpid;
1402
1403         snprintf(cmd, sizeof cmd, imagecmd, filename);
1404         childpid = fork();
1405         if (childpid < 0) {
1406                 unlink(filename);
1407                 return childpid;
1408         }
1409
1410         if (childpid == 0) {
1411                 int retcode;
1412                 pid_t grandchildpid;
1413
1414                 grandchildpid = fork();
1415                 if (grandchildpid < 0) {
1416                         return grandchildpid;
1417                 }
1418
1419                 if (grandchildpid == 0) {
1420                         int nullfd;
1421                         int outfd = -1;
1422                         int errfd = -1;
1423
1424                         nullfd = open("/dev/null", O_WRONLY);
1425                         if (nullfd > -1) {
1426                                 dup2(1, outfd);
1427                                 dup2(2, errfd);
1428                                 dup2(nullfd, 1);
1429                                 dup2(nullfd, 2);
1430                         }
1431                         retcode = system(cmd);
1432                         if (nullfd > -1) {
1433                                 dup2(outfd, 1);
1434                                 dup2(errfd, 2);
1435                                 close(nullfd);
1436                         }
1437                         unlink(filename);
1438                         exit(retcode);
1439                 }
1440
1441                 if (grandchildpid > 0) {
1442                         exit(0);
1443                 }
1444         }
1445
1446         if (childpid > 0) {
1447                 int retcode;
1448
1449                 waitpid(childpid, &retcode, 0);
1450                 return retcode;
1451         }
1452         
1453         return -1;
1454 }
1455
1456
1457 /*
1458  * View an image attached to a message
1459  */
1460 void image_view(CtdlIPC *ipc, unsigned long msg)
1461 {
1462         struct parts *ptr = last_message_parts;
1463         char part[SIZ];
1464         int found = 0;
1465
1466         /* Run through available parts */
1467         for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1468                 if ((!strcasecmp(ptr->disposition, "attachment")
1469                    || !strcasecmp(ptr->disposition, "inline"))
1470                    && !strncmp(ptr->mimetype, "image/", 6)) {
1471                         found++;
1472                         if (found == 1) {
1473                                 strcpy(part, ptr->number);
1474                         }
1475                 }
1476         }
1477
1478         while (found > 0) {
1479                 if (found > 1)
1480                         strprompt("View which part (0 when done)", part, SIZ-1);
1481                 found = -found;
1482                 for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1483                         if ((!strcasecmp(ptr->disposition, "attachment")
1484                            || !strcasecmp(ptr->disposition, "inline"))
1485                            && !strncmp(ptr->mimetype, "image/", 6)
1486                            && !strcasecmp(ptr->number, part)) {
1487                                 char tmp[PATH_MAX];
1488                                 char buf[SIZ];
1489                                 void *file = NULL; /* The downloaded file */
1490                                 int r;
1491         
1492                                 /* view image */
1493                                 found = -found;
1494                                 r = CtdlIPCAttachmentDownload(ipc, msg, ptr->number, &file, progress, buf);
1495                                 if (r / 100 != 2) {
1496                                         scr_printf("%s\n", buf);
1497                                 } else {
1498                                         size_t len;
1499         
1500                                         len = (size_t)extract_long(buf, 0);
1501                                         progress(ipc, len, len);
1502                                         scr_flush();
1503                                         CtdlMakeTempFileName(tmp, sizeof tmp);
1504                                         strcat(tmp, ptr->filename);
1505                                         save_buffer(file, len, tmp);
1506                                         free(file);
1507                                         do_image_view(tmp);
1508                                 }
1509                                 break;
1510                         }
1511                 }
1512                 if (found == 1)
1513                         break;
1514         }
1515 }
1516  
1517
1518 /*
1519  * Read the messages in the current room
1520  */
1521 void readmsgs(CtdlIPC *ipc,
1522         enum MessageList c,             /* see listing in citadel_ipc.h */
1523         enum MessageDirection rdir,     /* 1=Forward (-1)=Reverse */
1524         int q           /* Number of msgs to read (if c==3) */
1525 ) {
1526         int a, b, e, f, g, start;
1527         int savedpos;
1528         int hold_sw = 0;
1529         char arcflag = 0;
1530         char quotflag = 0;
1531         int hold_color = 0;
1532         char prtfile[PATH_MAX];
1533         char pagin;
1534         char cmd[SIZ];
1535         char targ[ROOMNAMELEN];
1536         char filename[PATH_MAX];
1537         char save_to[PATH_MAX];
1538         void *attachment = NULL;        /* Downloaded attachment */
1539         FILE *dest = NULL;              /* Alternate destination other than screen */
1540         int r;                          /* IPC response code */
1541         static int att_seq = 0;         /* Attachment download sequence number */
1542         int rv = 0;                     /* silence the stupid warn_unused_result warnings */
1543
1544         if (c < 0)
1545                 b = (num_msgs - 1);
1546         else
1547                 b = 0;
1548
1549         CtdlMakeTempFileName(prtfile, sizeof prtfile);
1550
1551         if (msg_arr) {
1552                 free(msg_arr);
1553                 msg_arr = NULL;
1554         }
1555         r = CtdlIPCGetMessages(ipc, c, q, NULL, &msg_arr, cmd);
1556         if (r / 100 != 1) {
1557                 scr_printf("%s\n", cmd);
1558         } else {
1559                 for (num_msgs = 0; msg_arr[num_msgs]; num_msgs++)
1560                         ;
1561         }
1562
1563         if (num_msgs == 0) {    /* TODO look at this later */
1564                 if (c == LastMessages) return;
1565                 scr_printf("*** There are no ");
1566                 if (c == NewMessages) scr_printf("new ");
1567                 if (c == OldMessages) scr_printf("old ");
1568                 scr_printf("messages in this room.\n");
1569                 return;
1570         }
1571
1572         lines_printed = 0;
1573
1574         /* this loop cycles through each message... */
1575         start = ((rdir == 1) ? 0 : (num_msgs - 1));
1576         for (a = start; ((a < num_msgs) && (a >= 0)); a = a + rdir) {
1577                 while (msg_arr[a] == 0L) {
1578                         a = a + rdir;
1579                         if ((a == num_msgs) || (a == (-1)))
1580                                 return;
1581                 }
1582
1583 RAGAIN:         pagin = ((arcflag == 0)
1584                          && (quotflag == 0)
1585                          && (userflags & US_PAGINATOR)) ? 1 : 0;
1586
1587                 /* If we're doing a quote, set the screenwidth to 72 */
1588                 if (quotflag) {
1589                         hold_sw = screenwidth;
1590                         screenwidth = 72;
1591                 }
1592
1593                 /* If printing or archiving, set the screenwidth to 80 */
1594                 if (arcflag) {
1595                         hold_sw = screenwidth;
1596                         screenwidth = 80;
1597                 }
1598
1599                 /* clear parts list */
1600                 free_parts(last_message_parts);
1601                 last_message_parts = NULL;
1602
1603                 /* now read the message... */
1604                 e = read_message(ipc, msg_arr[a], pagin, dest);
1605
1606                 /* ...and set the screenwidth back if we have to */
1607                 if ((quotflag) || (arcflag)) {
1608                         screenwidth = hold_sw;
1609                 }
1610 RMSGREAD:       scr_flush();
1611                 highest_msg_read = msg_arr[a];
1612                 if (quotflag) {
1613                         fclose(dest);
1614                         dest = NULL;
1615                         quotflag = 0;
1616                         enable_color = hold_color;
1617                         process_quote();
1618                         e = 'r';
1619                         goto DONE_QUOTING;
1620                 }
1621                 if (arcflag) {
1622                         fclose(dest);
1623                         dest = NULL;
1624                         arcflag = 0;
1625                         enable_color = hold_color;
1626                         f = fork();
1627                         if (f == 0) {
1628                                 if (freopen(prtfile, "r", stdin) == NULL) {
1629                                         /* we probably should handle the error condition here */
1630                                 }
1631                                 screen_reset();
1632                                 stty_ctdl(SB_RESTORE);
1633                                 ka_system(printcmd);
1634                                 stty_ctdl(SB_NO_INTR);
1635                                 screen_set();
1636                                 unlink(prtfile);
1637                                 exit(0);
1638                         }
1639                         if (f > 0)
1640                                 do {
1641                                         g = wait(NULL);
1642                                 } while ((g != f) && (g >= 0));
1643                         scr_printf("Message printed.\n");
1644                 }
1645                 if (rc_alt_semantics && c == 1) {
1646                         char buf[SIZ];
1647
1648                         r = CtdlIPCSetMessageSeen(ipc, msg_arr[a], 1, buf);
1649                 }
1650                 if (e == SIGQUIT)
1651                         return;
1652                 if (((userflags & US_NOPROMPT) || (e == SIGINT))
1653                         && (((room_flags & QR_MAILBOX) == 0)
1654                         || (rc_force_mail_prompts == 0))) {
1655                         e = 'n';
1656                 } else {
1657                         color(DIM_WHITE);
1658                         scr_printf("(");
1659                         color(BRIGHT_WHITE);
1660                         scr_printf("%d", num_msgs - a - 1);
1661                         color(DIM_WHITE);
1662                         scr_printf(") ");
1663
1664                         keyopt("<B>ack <A>gain <R>eply reply<Q>uoted <N>ext <S>top ");
1665                         if (rc_url_cmd[0] && num_urls)
1666                                 keyopt("<U>RLview ");
1667                         if (has_images > 0 && !IsEmptyStr(imagecmd))
1668                                 keyopt("<I>mages ");
1669                         keyopt("<?>help -> ");
1670
1671                         do {
1672                                 lines_printed = 2;
1673                                 e = (inkey() & 127);
1674                                 e = tolower(e);
1675 /* return key same as <N> */ if (e == 10)
1676                                         e = 'n';
1677 /* space key same as <N> */ if (e == 32)
1678                                         e = 'n';
1679 /* del/move for aides only */
1680                                     if (  (!is_room_aide)
1681                                        && ((room_flags & QR_MAILBOX) == 0)
1682                                        && ((room_flags2 & QR2_COLLABDEL) == 0)
1683                                        ) {
1684                                         if ((e == 'd') || (e == 'm'))
1685                                                 e = 0;
1686                                 }
1687 /* print only if available */
1688                                 if ((e == 'p') && (IsEmptyStr(printcmd)))
1689                                         e = 0;
1690 /* can't file if not allowed */
1691                                     if ((e == 'f')
1692                                         && (rc_allow_attachments == 0))
1693                                         e = 0;
1694 /* link only if browser avail*/
1695                                     if ((e == 'u')
1696                                         && (IsEmptyStr(rc_url_cmd)))
1697                                         e = 0;
1698                                 if ((e == 'i')
1699                                         && (IsEmptyStr(imagecmd) || !has_images))
1700                                         e = 0;
1701                         } while ((e != 'a') && (e != 'n') && (e != 's')
1702                                  && (e != 'd') && (e != 'm') && (e != 'p')
1703                                  && (e != 'q') && (e != 'b') && (e != 'h')
1704                                  && (e != 'r') && (e != 'f') && (e != '?')
1705                                  && (e != 'u') && (e != 'c') && (e != 'y')
1706                                  && (e != 'i') && (e != 'o') );
1707                         switch (e) {
1708                         case 's':
1709                                 scr_printf("Stop");
1710                                 break;
1711                         case 'a':
1712                                 scr_printf("Again");
1713                                 break;
1714                         case 'd':
1715                                 scr_printf("Delete");
1716                                 break;
1717                         case 'm':
1718                                 scr_printf("Move");
1719                                 break;
1720                         case 'c':
1721                                 scr_printf("Copy");
1722                                 break;
1723                         case 'n':
1724                                 scr_printf("Next");
1725                                 break;
1726                         case 'p':
1727                                 scr_printf("Print");
1728                                 break;
1729                         case 'q':
1730                                 scr_printf("reply Quoted");
1731                                 break;
1732                         case 'b':
1733                                 scr_printf("Back");
1734                                 break;
1735                         case 'h':
1736                                 scr_printf("Header");
1737                                 break;
1738                         case 'r':
1739                                 scr_printf("Reply");
1740                                 break;
1741                         case 'o':
1742                                 scr_printf("Open attachments");
1743                                 break;
1744                         case 'f':
1745                                 scr_printf("File");
1746                                 break;
1747                         case 'u':
1748                                 scr_printf("URL's");
1749                                 break;
1750                         case 'y':
1751                                 scr_printf("mY next");
1752                                 break;
1753                         case 'i':
1754                                 break;
1755                         case '?':
1756                                 scr_printf("? <help>");
1757                                 break;
1758                         }
1759                         if (userflags & US_DISAPPEAR || e == 'i')
1760                                 scr_printf("\r%79s\r", "");
1761                         else
1762                                 scr_printf("\n");
1763                         scr_flush();
1764                 }
1765 DONE_QUOTING:   switch (e) {
1766                 case '?':
1767                         scr_printf("Options available here:\n"
1768                                 " ?  Help (prints this message)\n"
1769                                 " S  Stop reading immediately\n"
1770                                 " A  Again (repeats last message)\n"
1771                                 " N  Next (continue with next message)\n"
1772                                 " Y  My Next (continue with next message you authored)\n"
1773                                 " B  Back (go back to previous message)\n");
1774                         if (  (is_room_aide)
1775                            || (room_flags & QR_MAILBOX)
1776                            || (room_flags2 & QR2_COLLABDEL)
1777                         ) {
1778                                 scr_printf(" D  Delete this message\n"
1779                                         " M  Move message to another room\n");
1780                         }
1781                         scr_printf(" C  Copy message to another room\n");
1782                         if (!IsEmptyStr(printcmd))
1783                                 scr_printf(" P  Print this message\n");
1784                         scr_printf(
1785                                 " Q  Reply to this message, quoting portions of it\n"
1786                                 " H  Headers (display message headers only)\n");
1787                         if (is_mail)
1788                                 scr_printf(" R  Reply to this message\n");
1789                         if (rc_allow_attachments) {
1790                                 scr_printf(" O  (Open attachments)\n");
1791                                 scr_printf(" F  (save attachments to a File)\n");
1792                         }
1793                         if (!IsEmptyStr(rc_url_cmd))
1794                                 scr_printf(" U  (list URL's for display)\n");
1795                         if (!IsEmptyStr(imagecmd) && has_images > 0)
1796                                 scr_printf(" I  Image viewer\n");
1797                         scr_printf("\n");
1798                         goto RMSGREAD;
1799                 case 'p':
1800                         scr_flush();
1801                         dest = fopen(prtfile, "w");
1802                         arcflag = 1;
1803                         hold_color = enable_color;
1804                         enable_color = 0;
1805                         goto RAGAIN;
1806                 case 'q':
1807                         scr_flush();
1808                         dest = fopen(temp2, "w");
1809                         quotflag = 1;
1810                         hold_color = enable_color;
1811                         enable_color = 0;
1812                         goto RAGAIN;
1813                 case 's':
1814                         return;
1815                 case 'a':
1816                         goto RAGAIN;
1817                 case 'b':
1818                         a = a - (rdir * 2);
1819                         break;
1820                 case 'm':
1821                 case 'c':
1822                         newprompt("Enter target room: ",
1823                                   targ, ROOMNAMELEN - 1);
1824                         if (!IsEmptyStr(targ)) {
1825                                 r = CtdlIPCMoveMessage(ipc, (e == 'c' ? 1 : 0),
1826                                                        msg_arr[a], targ, cmd);
1827                                 scr_printf("%s\n", cmd);
1828                                 if (r / 100 == 2)
1829                                         msg_arr[a] = 0L;
1830                         } else {
1831                                 goto RMSGREAD;
1832                         }
1833                         if (r / 100 != 2)       /* r will be init'ed, FIXME */
1834                                 goto RMSGREAD;  /* the logic here sucks */
1835                         break;
1836                 case 'o':
1837                 case 'f':
1838                         newprompt("Which section? ", filename, ((sizeof filename) - 1));
1839                         r = CtdlIPCAttachmentDownload(ipc, msg_arr[a],
1840                                         filename, &attachment, progress, cmd);
1841                         if (r / 100 != 2) {
1842                                 scr_printf("%s\n", cmd);
1843                         } else {
1844                                 extract_token(filename, cmd, 2, '|', sizeof filename);
1845                                 /*
1846                                  * Part 1 won't have a filename; use the
1847                                  * subject of the message instead. IO
1848                                  */
1849                                 if (IsEmptyStr(filename)) {
1850                                         strcpy(filename, reply_subject);
1851                                 }
1852                                 if (e == 'o') {         /* open attachment */
1853                                         mkdir(tempdir, 0700);
1854                                         snprintf(save_to, sizeof save_to, "%s/%04x.%s",
1855                                                 tempdir,
1856                                                 ++att_seq,
1857                                                 filename);
1858                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1859                                         snprintf(cmd, sizeof cmd, rc_open_cmd, save_to);
1860                                         rv = system(cmd);
1861                                 }
1862                                 else {                  /* save attachment to disk */
1863                                         destination_directory(save_to, filename);
1864                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1865                                 }
1866                         }
1867                         if (attachment) {
1868                                 free(attachment);
1869                                 attachment = NULL;
1870                         }
1871                         goto RMSGREAD;
1872                 case 'd':
1873                         scr_printf("*** Delete this message? ");
1874                         if (yesno() == 1) {
1875                                 r = CtdlIPCDeleteMessage(ipc, msg_arr[a], cmd);
1876                                 scr_printf("%s\n", cmd);
1877                                 if (r / 100 == 2)
1878                                         msg_arr[a] = 0L;
1879                         } else {
1880                                 goto RMSGREAD;
1881                         }
1882                         break;
1883                 case 'h':
1884                         read_message(ipc, msg_arr[a], READ_HEADER, NULL);
1885                         goto RMSGREAD;
1886                 case 'r':
1887                         savedpos = num_msgs;
1888                         entmsg(ipc, 1, ((userflags & US_EXTEDIT) ? 2 : 0), 0);
1889                         num_msgs = savedpos;
1890                         goto RMSGREAD;
1891                 case 'u':
1892                         list_urls(ipc);
1893                         goto RMSGREAD;
1894                 case 'i':
1895                         image_view(ipc, msg_arr[a]);
1896                         goto RMSGREAD;
1897             case 'y':
1898           { /* hack hack hack */
1899             /* find the next message by me, stay here if we find nothing */
1900             int finda;
1901             int lasta = a;
1902             for (finda = (a + rdir); ((finda < num_msgs) && (finda >= 0)); finda += rdir)
1903               {
1904                 /* This is repetitively dumb, but that's what computers are for.
1905                    We have to load up messages until we find one by us */
1906                 char buf[SIZ];
1907                 int founda = 0;
1908                 struct ctdlipcmessage *msg = NULL;
1909                 
1910                 /* read the header so we can get 'from=' */
1911                 r = CtdlIPCGetSingleMessage(ipc, msg_arr[finda], 1, 0, &msg, buf);
1912                 if (!strncasecmp(msg->author, fullname, sizeof(fullname))) {
1913                         a = lasta; /* meesa current */
1914                         founda = 1;
1915                 }
1916
1917                 free(msg);
1918
1919                 if (founda)
1920                         break; /* for */
1921                 lasta = finda; /* keep one behind or we skip on the reentrance to the for */
1922               } /* for */
1923           } /* case 'y' */
1924       } /* switch */
1925         }                       /* end for loop */
1926 }                               /* end read routine */
1927
1928
1929
1930
1931 /*
1932  * View and edit a system message
1933  */
1934 void edit_system_message(CtdlIPC *ipc, char *which_message)
1935 {
1936         char desc[SIZ];
1937         char read_cmd[SIZ];
1938         char write_cmd[SIZ];
1939
1940         snprintf(desc, sizeof desc, "system message '%s'", which_message);
1941         snprintf(read_cmd, sizeof read_cmd, "MESG %s", which_message);
1942         snprintf(write_cmd, sizeof write_cmd, "EMSG %s", which_message);
1943         do_edit(ipc, desc, read_cmd, "NOOP", write_cmd);
1944 }
1945
1946
1947
1948
1949 /*
1950  * Verify the message base
1951  */
1952 void check_message_base(CtdlIPC *ipc)
1953 {
1954         char buf[SIZ];
1955         char *transcript = NULL;
1956         int r;          /* IPC response code */
1957
1958         scr_printf
1959             ("Please read the documentation before running this command.\n"
1960             "Having done so, do you still want to check the message base? ");
1961         if (yesno() == 0)
1962                 return;
1963
1964         r = CtdlIPCMessageBaseCheck(ipc, &transcript, buf);
1965         if (r / 100 != 1) {
1966                 scr_printf("%s\n", buf);
1967                 return;
1968         }
1969
1970         while (transcript && !IsEmptyStr(transcript)) {
1971                 lines_printed = 1;
1972                 extract_token(buf, transcript, 0, '\n', sizeof buf);
1973                 remove_token(transcript, 0, '\n');
1974                 pprintf("%s\n", buf);
1975         }
1976         if (transcript) free(transcript);
1977         return;
1978 }
1979
1980
1981 /*
1982  * Loads the contents of a file into memory.  Caller must free the allocated
1983  * memory.
1984  */
1985 char *load_message_from_file(FILE *src)
1986 {
1987         size_t i;
1988         size_t got = 0;
1989         char *dest = NULL;
1990
1991         fseek(src, 0, SEEK_END);
1992         i = ftell(src);
1993         rewind(src);
1994
1995         dest = (char *)calloc(1, i + 1);
1996         if (!dest)
1997                 return NULL;
1998
1999         while (got < i) {
2000                 size_t g;
2001
2002                 g = fread(dest + got, 1, i - got, src);
2003                 got += g;
2004                 if (g < i - got) {
2005                         /* Interrupted system call, keep going */
2006                         if (errno == EINTR)
2007                                 continue;
2008                         /* At this point we have either EOF or error */
2009                         i = got;
2010                         break;
2011                 }
2012                 dest[i] = 0;
2013         }
2014
2015         return dest;
2016 }