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