c800b7f9049b0ae16e91aef845f1ff21dc3e9789
[citadel.git] / textclient / src / messages.c
1 /*
2  * Text client functions for reading and writing of messages
3  *
4  * Copyright (c) 1987-2016 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("hnod=%s\nroom=%s\nnode=%s\ntime=%s",
497                                 message->hnod, message->room,
498                                 message->node, 
499                                 asctime(localtime(&message->time)));
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 (!IsEmptyStr(message->node)) {
566                         if ((room_flags & QR_NETWORK)
567                             || ((strcasecmp(message->node, ipc->ServInfo.nodename)
568                              && (strcasecmp(message->node, ipc->ServInfo.fqdn))))) {
569                                 if (IsEmptyStr(message->email)) {
570                                         if (dest) {
571                                                 fprintf(dest, "@%s ", message->node);
572                                         } else {
573                                                 color(DIM_WHITE);
574                                                 scr_printf("@");
575                                                 color(BRIGHT_YELLOW);
576                                                 scr_printf("%s ", message->node);
577                                         }
578                                 }
579                         }
580                 }
581                 if (strcasecmp(message->hnod, ipc->ServInfo.humannode)
582                     && (!IsEmptyStr(message->hnod)) && (IsEmptyStr(message->email))) {
583                         if (dest) {
584                                 fprintf(dest, "(%s) ", message->hnod);
585                         } else {
586                                 color(DIM_WHITE);
587                                 scr_printf("(");
588                                 color(BRIGHT_WHITE);
589                                 scr_printf("%s", message->hnod);
590                                 color(DIM_WHITE);
591                                 scr_printf(") ");
592                         }
593                 }
594                 if (strcasecmp(message->room, room_name) && (IsEmptyStr(message->email))) {
595                         if (dest) {
596                                 fprintf(dest, "in %s> ", message->room);
597                         } else {
598                                 color(DIM_WHITE);
599                                 scr_printf("in ");
600                                 color(BRIGHT_MAGENTA);
601                                 scr_printf("%s> ", message->room);
602                         }
603                 }
604                 if (!IsEmptyStr(message->recipient)) {
605                         if (dest) {
606                                 fprintf(dest, "to %s ", message->recipient);
607                         } else {
608                                 color(DIM_WHITE);
609                                 scr_printf("to ");
610                                 color(BRIGHT_CYAN);
611                                 scr_printf("%s ", message->recipient);
612                         }
613                 }
614         }
615         
616         if (dest) {
617                 fprintf(dest, "\n");
618         } else {
619                 scr_printf("\n");
620         }
621
622         /* Set the reply-to address to an Internet e-mail address if possible
623          */
624         if ((message->email != NULL) && (!IsEmptyStr(message->email))) {
625                 if (!IsEmptyStr(message->author)) {
626                         snprintf(reply_to, sizeof reply_to, "%s <%s>", message->author, message->email);
627                 }
628                 else {
629                         safestrncpy(reply_to, message->email, sizeof reply_to);
630                 }
631         }
632
633         /* But if we can't do that, set it to a Citadel address.
634          */
635         if (!strcmp(reply_to, NO_REPLY_TO)) {
636                 snprintf(reply_to, sizeof(reply_to), "%s @ %s",
637                          message->author, message->node);
638         }
639
640         if (message->msgid != NULL) {
641                 safestrncpy(reply_inreplyto, message->msgid, sizeof reply_inreplyto);
642         }
643
644         if (message->references != NULL) if (!IsEmptyStr(message->references)) {
645                 safestrncpy(reply_references, message->references, sizeof reply_references);
646         }
647
648         if (message->subject != NULL) {
649                 safestrncpy(reply_subject, message->subject, sizeof reply_subject);
650                 if (!IsEmptyStr(message->subject)) {
651                         if (dest) {
652                                 fprintf(dest, "Subject: %s\n", message->subject);
653                         } else {
654                                 color(DIM_WHITE);
655                                 scr_printf("Subject: ");
656                                 color(BRIGHT_CYAN);
657                                 mini_2047_decode(message->subject);
658                                 scr_printf("%s\n", message->subject);
659                         }
660                 }
661         }
662
663         if (pagin == 1 && !dest) {
664                 color(BRIGHT_WHITE);
665         }
666
667         /******* end of header output, start of message text output *******/
668
669         /*
670          * Convert HTML to plain text, formatting for the actual width
671          * of the client screen.
672          */
673         if (!strcasecmp(message->content_type, "text/html")) {
674                 converted_text = html_to_ascii(message->text, 0, screenwidth, 0);
675                 if (converted_text != NULL) {
676                         free(message->text);
677                         message->text = converted_text;
678                         format_type = 1;
679                 }
680         }
681
682         /* Text/plain is a different type */
683         if (!strcasecmp(message->content_type, "text/plain")) {
684                 format_type = 1;
685         }
686
687         /* Extract URL's */
688         static char *urlprefixes[] = {
689                 "http://",
690                 "https://",
691                 "ftp://"
692         };
693         int p = 0;
694         num_urls = 0;   /* Start with a clean slate */
695         for (p=0; p<(sizeof urlprefixes / sizeof(char *)); ++p) {
696                 searchptr = message->text;
697                 while ( (searchptr != NULL) && (num_urls < MAXURLS) ) {
698                         searchptr = strstr(searchptr, urlprefixes[p]);
699                         if (searchptr != NULL) {
700                                 safestrncpy(urls[num_urls], searchptr, sizeof(urls[num_urls]));
701                                 for (i = 0; i < strlen(urls[num_urls]); i++) {
702                                         ch = urls[num_urls][i];
703                                         if (ch == '>' || ch == '\"' || ch == ')' ||
704                                             ch == ' ' || ch == '\n') {
705                                                 urls[num_urls][i] = 0;
706                                                 break;
707                                         }
708                                 }
709                                 num_urls++;
710                                 ++searchptr;
711                         }
712                 }
713         }
714
715         /*
716          * Here we go
717          */
718         if (format_type == 0) {
719                 fr = fmout(screenwidth, NULL, message->text, dest, 1);
720         } else {
721                 /* renderer for text/plain */
722
723                 lineptr = message->text;
724
725                 do {
726                         nextline = strchr(lineptr, '\n');
727                         if (nextline != NULL) {
728                                 *nextline = 0;
729                                 ++nextline;
730                                 if (*nextline == 0) nextline = NULL;
731                         }
732
733                         if (sigcaught == 0) {
734                                 linelen = strlen(lineptr);
735                                 if (linelen && (lineptr[linelen-1] == '\r')) {
736                                         lineptr[--linelen] = 0;
737                                 }
738                                 if (dest) {
739                                         fprintf(dest, "%s\n", lineptr);
740                                 } else {
741                                         scr_printf("%s\n", lineptr);
742                                 }
743                         }
744                         if (lineptr[0] == 0) final_line_is_blank = 1;
745                         else final_line_is_blank = 0;
746                         lineptr = nextline;
747                 } while (nextline);
748                 fr = sigcaught;
749         }
750         if (!final_line_is_blank) {
751                 if (dest) {
752                         fprintf(dest, "\n");
753                 }
754                 else {
755                         scr_printf("\n");
756                         fr = sigcaught;         
757                 }
758         }
759
760         /* Enumerate any attachments */
761         if ( (pagin == 1) && (message->attachments) ) {
762                 struct parts *ptr;
763
764                 for (ptr = message->attachments; ptr; ptr = ptr->next) {
765                         if ( (!strcasecmp(ptr->disposition, "attachment"))
766                            || (!strcasecmp(ptr->disposition, "inline"))
767                            || (!strcasecmp(ptr->disposition, ""))
768                         ) {
769                                 if ( (strcasecmp(ptr->number, message->mime_chosen))
770                                    && (!IsEmptyStr(ptr->mimetype))
771                                 ) {
772                                         color(DIM_WHITE);
773                                         scr_printf("Part ");
774                                         color(BRIGHT_MAGENTA);
775                                         scr_printf("%s", ptr->number);
776                                         color(DIM_WHITE);
777                                         scr_printf(": ");
778                                         color(BRIGHT_CYAN);
779                                         scr_printf("%s", ptr->filename);
780                                         color(DIM_WHITE);
781                                         scr_printf(" (%s, %ld bytes)\n", ptr->mimetype, ptr->length);
782                                         if (!strncmp(ptr->mimetype, "image/", 6)) {
783                                                 has_images++;
784                                         }
785                                 }
786                         }
787                 }
788         }
789
790         /* Save the attachments info for later */
791         last_message_parts = message->attachments;
792
793         /* Now we're done */
794         free(message->text);
795         free(message);
796
797         if (pagin == 1 && !dest)
798                 color(DIM_WHITE);
799         stty_ctdl(0);
800         return (fr);
801 }
802
803 /*
804  * replace string function for the built-in editor
805  */
806 void replace_string(char *filename, long int startpos)
807 {
808         char buf[512];
809         char srch_str[128];
810         char rplc_str[128];
811         FILE *fp;
812         int a;
813         long rpos, wpos;
814         char *ptr;
815         int substitutions = 0;
816         long msglen = 0L;
817         int rv;
818
819         newprompt("Enter text to be replaced: ", srch_str, (sizeof(srch_str)-1) );
820         if (IsEmptyStr(srch_str)) {
821                 return;
822         }
823
824         newprompt("Enter text to replace it with: ", rplc_str, (sizeof(rplc_str)-1) );
825
826         fp = fopen(filename, "r+");
827         if (fp == NULL) {
828                 return;
829         }
830
831         wpos = startpos;
832         fseek(fp, startpos, 0);
833         strcpy(buf, "");
834         while (a = getc(fp), a > 0) {
835                 ++msglen;
836                 buf[strlen(buf) + 1] = 0;
837                 buf[strlen(buf)] = a;
838                 if (strlen(buf) >= strlen(srch_str)) {
839                         ptr = (&buf[strlen(buf) - strlen(srch_str)]);
840                         if (!strncmp(ptr, srch_str, strlen(srch_str))) {
841                                 strcpy(ptr, rplc_str);
842                                 ++substitutions;
843                         }
844                 }
845                 if (strlen(buf) > 384) {
846                         rpos = ftell(fp);
847                         fseek(fp, wpos, 0);
848                         rv = fwrite((char *) buf, 128, 1, fp);
849                         if (rv < 0) {
850                                 scr_printf("failed to replace string: %s\n", strerror(errno));
851                                 break; /*whoopsi! */
852                         }
853                         strcpy(buf, &buf[128]);
854                         wpos = ftell(fp);
855                         fseek(fp, rpos, 0);
856                 }
857         }
858         fseek(fp, wpos, 0);
859         if (!IsEmptyStr(buf)) {
860                 rv = fwrite((char *) buf, strlen(buf), 1, fp);
861         }
862         wpos = ftell(fp);
863         fclose(fp);
864         rv = truncate(filename, wpos);
865         scr_printf("<R>eplace made %d substitution(s).\n\n", substitutions);
866 }
867
868 /*
869  * Function to begin composing a new message
870  */
871 int client_make_message(CtdlIPC *ipc,
872                         char *filename,         /* temporary file name */
873                         char *recipient,        /* NULL if it's not mail */
874                         int is_anonymous,
875                         int format_type,
876                         int mode,
877                         char *subject,          /* buffer to store subject line */
878                         int subject_required
879 ) {
880         FILE *fp;
881         int a, b, e_ex_code;
882         long beg;
883         char datestr[256];
884         char header[SIZ];
885         int cksum = 0;
886
887         if ( (mode == 2) && (IsEmptyStr(editor_path)) ) {
888                 scr_printf("*** No editor available; using built-in editor.\n");
889                 mode = 0;
890         }
891
892         struct tm thetime;
893         time_t now = time(NULL);
894         localtime_r(&now, &thetime);
895         strftime(datestr, sizeof datestr, "%F %R", &thetime);
896         header[0] = 0;
897
898         if (room_flags & QR_ANONONLY && !recipient) {
899                 snprintf(header, sizeof header, " ****");
900         }
901         else {
902                 snprintf(header, sizeof header,
903                         " %s from %s",
904                         datestr,
905                         (is_anonymous ? "[anonymous]" : fullname)
906                         );
907                 if (!IsEmptyStr(recipient)) {
908                         size_t tmp = strlen(header);
909                         snprintf(&header[tmp], sizeof header - tmp,
910                                 " to %s", recipient);
911                 }
912         }
913         scr_printf("%s\n", header);
914         if (subject != NULL) if (!IsEmptyStr(subject)) {
915                 scr_printf("Subject: %s\n", subject);
916         }
917         
918         if ( (subject_required) && (IsEmptyStr(subject)) ) {
919                 newprompt("Subject: ", subject, 70);
920         }
921
922         if (mode == 1) {
923                 scr_printf("(Press ctrl-d when finished)\n");
924         }
925
926         if (mode == 0) {
927                 fp = fopen(filename, "r");
928                 if (fp != NULL) {
929                         fmout(screenwidth, fp, NULL, NULL, 0);
930                         beg = ftell(fp);
931                         if (beg < 0)
932                                 scr_printf("failed to get stream position %s\n", 
933                                            strerror(errno));
934                         fclose(fp);
935                 } else {
936                         fp = fopen(filename, "w");
937                         if (fp == NULL) {
938                                 scr_printf("*** Error opening temp file!\n    %s: %s\n",
939                                         filename, strerror(errno)
940                                 );
941                         return(1);
942                         }
943                         fclose(fp);
944                 }
945         }
946
947 ME1:    switch (mode) {
948
949         case 0:
950                 fp = fopen(filename, "r+");
951                 if (fp == NULL) {
952                         scr_printf("*** Error opening temp file!\n    %s: %s\n",
953                                 filename, strerror(errno)
954                         );
955                         return(1);
956                 }
957                 citedit(fp);
958                 fclose(fp);
959                 goto MECR;
960
961         case 1:
962                 fp = fopen(filename, "a");
963                 if (fp == NULL) {
964                         scr_printf("*** Error opening temp file!\n"
965                                 "    %s: %s\n",
966                                 filename, strerror(errno));
967                         return(1);
968                 }
969                 do {
970                         a = inkey();
971                         if (a == 255)
972                                 a = 32;
973                         if (a == 13)
974                                 a = 10;
975                         if (a != 4) {
976                                 putc(a, fp);
977                                 scr_putc(a);
978                         }
979                         if (a == 10)
980                                 scr_putc(10);
981                 } while (a != 4);
982                 fclose(fp);
983                 break;
984
985         case 2:
986         default:        /* allow 2+ modes */
987                 e_ex_code = 1;  /* start with a failed exit code */
988                 stty_ctdl(SB_RESTORE);
989                 editor_pid = fork();
990                 cksum = file_checksum(filename);
991                 if (editor_pid == 0) {
992                         char tmp[SIZ];
993
994                         chmod(filename, 0600);
995                         snprintf(tmp, sizeof tmp, "WINDOW_TITLE=%s", header);
996                         putenv(tmp);
997                         execlp(editor_path, editor_path, filename, NULL);
998                         exit(1);
999                 }
1000                 if (editor_pid > 0)
1001                         do {
1002                                 e_ex_code = 0;
1003                                 b = ka_wait(&e_ex_code);
1004                         } while ((b != editor_pid) && (b >= 0));
1005                 editor_pid = (-1);
1006                 stty_ctdl(0);
1007                 break;
1008         }
1009
1010 MECR:   if (mode >= 2) {
1011                 if (file_checksum(filename) == cksum) {
1012                         scr_printf("*** Aborted message.\n");
1013                         e_ex_code = 1;
1014                 }
1015                 if (e_ex_code == 0) {
1016                         goto MEFIN;
1017                 }
1018                 goto MEABT2;
1019         }
1020
1021         b = keymenu("Entry command (? for options)",
1022                 "<A>bort|"
1023                 "<C>ontinue|"
1024                 "<S>ave message|"
1025                 "<P>rint formatted|"
1026                 "add s<U>bject|"
1027                 "<R>eplace string|"
1028                 "<H>old message"
1029         );
1030
1031         if (b == 'a') goto MEABT;
1032         if (b == 'c') goto ME1;
1033         if (b == 's') goto MEFIN;
1034         if (b == 'p') {
1035                 scr_printf(" %s from %s", datestr, fullname);
1036                 if (!IsEmptyStr(recipient)) {
1037                         scr_printf(" to %s", recipient);
1038                 }
1039                 scr_printf("\n");
1040                 if (subject != NULL) if (!IsEmptyStr(subject)) {
1041                         scr_printf("Subject: %s\n", subject);
1042                 }
1043                 fp = fopen(filename, "r");
1044                 if (fp != NULL) {
1045                         fmout(screenwidth, fp, NULL, NULL, 0);
1046                         beg = ftell(fp);
1047                         if (beg < 0)
1048                                 scr_printf("failed to get stream position %s\n", 
1049                                            strerror(errno));
1050                         fclose(fp);
1051                 }
1052                 goto MECR;
1053         }
1054         if (b == 'r') {
1055                 replace_string(filename, 0L);
1056                 goto MECR;
1057         }
1058         if (b == 'h') {
1059                 return (2);
1060         }
1061         if (b == 'u') {
1062                 if (subject != NULL) {
1063                         newprompt("Subject: ", subject, 70);
1064                 }
1065                 goto MECR;
1066         }
1067
1068 MEFIN:  return (0);
1069
1070 MEABT:  scr_printf("Are you sure? ");
1071         if (yesno() == 0) {
1072                 goto ME1;
1073         }
1074 MEABT2: unlink(filename);
1075         return (2);
1076 }
1077
1078
1079 /*
1080  * Make sure there's room in msg_arr[] for at least one more.
1081  */
1082 void check_msg_arr_size(void) {
1083         if ((num_msgs + 1) > msg_arr_size) {
1084                 msg_arr_size += 512;
1085                 msg_arr = realloc(msg_arr,
1086                         ((sizeof(long)) * msg_arr_size) );
1087         }
1088 }
1089
1090
1091 /*
1092  * break_big_lines()  -  break up lines that are >1024 characters
1093  *                       otherwise the server will truncate
1094  */
1095 void break_big_lines(char *msg) {
1096         char *ptr;
1097         char *break_here;
1098
1099         if (msg == NULL) {
1100                 return;
1101         }
1102
1103         ptr = msg;
1104         while (strlen(ptr) > 1000) {
1105                 break_here = strchr(&ptr[900], ' ');
1106                 if ((break_here == NULL) || (break_here > &ptr[999])) {
1107                         break_here = &ptr[999];
1108                 }
1109                 *break_here = '\n';
1110                 ptr = break_here++;
1111         }
1112 }
1113
1114
1115 /*
1116  * entmsg()  -  edit and create a message
1117  *              returns 0 if message was saved
1118  */
1119 int entmsg(CtdlIPC *ipc,
1120                 int is_reply,   /* nonzero if this was a <R>eply command */
1121                 int c,          /* mode */
1122                 int masquerade  /* prompt for a non-default display name? */
1123 ) {
1124         char buf[SIZ];
1125         int a, b;
1126         int need_recp = 0;
1127         int mode;
1128         long highmsg = 0L;
1129         FILE *fp;
1130         char subject[SIZ];
1131         struct ctdlipcmessage message;
1132         unsigned long *msgarr = NULL;
1133         int r;                  /* IPC response code */
1134         int subject_required = 0;
1135
1136         if (!entmsg_ok) {
1137                 scr_printf("You may not enter messages in this type of room.\n");
1138                 return(1);
1139         }
1140
1141         if (c > 0) {
1142                 mode = 1;
1143         }
1144         else {
1145                 mode = 0;
1146         }
1147
1148         strcpy(subject, "");
1149
1150         /*
1151          * First, check to see if we have permission to enter a message in
1152          * this room.  The server will return an error code if we can't.
1153          */
1154         strcpy(message.recipient, "");
1155         strcpy(message.author, "");
1156         strcpy(message.subject, "");
1157         strcpy(message.references, "");
1158         message.text = "";              /* point to "", changes later */
1159         message.anonymous = 0;
1160         message.type = mode;
1161
1162         if (masquerade) {
1163                 newprompt("Display name for this message: ", message.author, 40);
1164         }
1165
1166         if (is_reply) {
1167
1168                 if (!IsEmptyStr(reply_subject)) {
1169                         if (!strncasecmp(reply_subject,
1170                            "Re: ", 3)) {
1171                                 strcpy(message.subject, reply_subject);
1172                         }
1173                         else {
1174                                 snprintf(message.subject,
1175                                         sizeof message.subject,
1176                                         "Re: %s",
1177                                         reply_subject);
1178                         }
1179                 }
1180
1181                 /* Trim down excessively long lists of thread references.  We eliminate the
1182                  * second one in the list so that the thread root remains intact.
1183                  */
1184                 int rrtok = num_tokens(reply_references, '|');
1185                 int rrlen = strlen(reply_references);
1186                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1187                         remove_token(reply_references, 1, '|');
1188                 }
1189
1190                 snprintf(message.references, sizeof message.references, "%s%s%s",
1191                         reply_references,
1192                         (IsEmptyStr(reply_references) ? "" : "|"),
1193                         reply_inreplyto
1194                 );
1195         }
1196
1197         r = CtdlIPCPostMessage(ipc, 0, &subject_required, &message, buf);
1198
1199         if (r / 100 != 2 && r / 10 != 57) {
1200                 scr_printf("%s\n", buf);
1201                 return (1);
1202         }
1203
1204         /* Error code 570 is special.  It means that we CAN enter a message
1205          * in this room, but a recipient needs to be specified.
1206          */
1207         need_recp = 0;
1208         if (r / 10 == 57) {
1209                 need_recp = 1;
1210         }
1211
1212         /* If the user is a dumbass, tell them how to type. */
1213         if ((userflags & US_EXPERT) == 0) {
1214                 formout(ipc, "entermsg");
1215         }
1216
1217         /* Handle the selection of a recipient, if necessary. */
1218         strcpy(buf, "");
1219         if (need_recp == 1) {
1220                 if (axlevel >= AxProbU) {
1221                         if (is_reply) {
1222                                 strcpy(buf, reply_to);
1223                         } else {
1224                                 newprompt("Enter recipient: ", buf, SIZ-100);
1225                                 if (IsEmptyStr(buf)) {
1226                                         return (1);
1227                                 }
1228                         }
1229                 } else
1230                         strcpy(buf, "sysop");
1231         }
1232         strcpy(message.recipient, buf);
1233
1234         if (room_flags & QR_ANONOPT) {
1235                 scr_printf("Anonymous (Y/N)? ");
1236                 if (yesno() == 1)
1237                         message.anonymous = 1;
1238         }
1239
1240         /* If it's mail, we've got to check the validity of the recipient... */
1241         if (!IsEmptyStr(message.recipient)) {
1242                 r = CtdlIPCPostMessage(ipc, 0, &subject_required,  &message, buf);
1243                 if (r / 100 != 2) {
1244                         scr_printf("%s\n", buf);
1245                         return (1);
1246                 }
1247         }
1248
1249         /* Learn the number of the newest message in in the room, so we can
1250          * tell upon saving whether someone else has posted too.
1251          */
1252         num_msgs = 0;
1253         r = CtdlIPCGetMessages(ipc, LastMessages, 1, NULL, &msgarr, buf);
1254         if (r / 100 != 1) {
1255                 scr_printf("%s\n", buf);
1256         } else {
1257                 for (num_msgs = 0; msgarr[num_msgs]; num_msgs++)
1258                         ;
1259         }
1260
1261         /* Now compose the message... */
1262         if (client_make_message(ipc, temp, message.recipient,
1263            message.anonymous, 0, c, message.subject, subject_required) != 0) {
1264             if (msgarr) free(msgarr);   
1265                 return (2);
1266         }
1267
1268         /* Reopen the temp file that was created, so we can send it */
1269         fp = fopen(temp, "r");
1270
1271         if (!fp || !(message.text = load_message_from_file(fp))) {
1272                 scr_printf("*** Internal error while trying to save message!\n"
1273                         "%s: %s\n",
1274                         temp, strerror(errno));
1275                 unlink(temp);
1276                 return(errno);
1277         }
1278
1279         if (fp) fclose(fp);
1280
1281         /* Break lines that are >1024 characters, otherwise the server
1282          * will truncate them.
1283          */
1284         break_big_lines(message.text);
1285
1286         /* Transmit message to the server */
1287         r = CtdlIPCPostMessage(ipc, 1, NULL, &message, buf);
1288         if (r / 100 != 4) {
1289                 scr_printf("%s\n", buf);
1290                 return (1);
1291         }
1292
1293         /* Yes, unlink it now, so it doesn't stick around if we crash */
1294         unlink(temp);
1295
1296         if (num_msgs >= 1) highmsg = msgarr[num_msgs - 1];
1297
1298         if (msgarr) free(msgarr);
1299         msgarr = NULL;
1300         r = CtdlIPCGetMessages(ipc, NewMessages, 0, NULL, &msgarr, buf);
1301         if (r / 100 != 1) {
1302                 scr_printf("%s\n", buf);
1303         } else {
1304                 for (num_msgs = 0; msgarr[num_msgs]; num_msgs++)
1305                         ;
1306         }
1307
1308         /* get new highest message number in room to set lrp for goto... */
1309         maxmsgnum = msgarr[num_msgs - 1];
1310
1311         /* now see if anyone else has posted in here */
1312         b = (-1);
1313         for (a = 0; a < num_msgs; ++a) {
1314                 if (msgarr[a] > highmsg) {
1315                         ++b;
1316                 }
1317         }
1318         if (msgarr) free(msgarr);
1319         msgarr = NULL;
1320
1321         /* In the Mail> room, this algorithm always counts one message
1322          * higher than in public rooms, so we decrement it by one.
1323          */
1324         if (need_recp) {
1325                 --b;
1326         }
1327
1328         if (b == 1) {
1329                 scr_printf("*** 1 additional message has been entered "
1330                         "in this room by another user.\n");
1331         }
1332         else if (b > 1) {
1333                 scr_printf("*** %d additional messages have been entered "
1334                         "in this room by other users.\n", b);
1335         }
1336     free(message.text);
1337
1338         return(0);
1339 }
1340
1341 /*
1342  * Do editing on a quoted file
1343  */
1344 void process_quote(void)
1345 {
1346         FILE *qfile, *tfile;
1347         char buf[128];
1348         int line, qstart, qend;
1349
1350         /* Unlink the second temp file as soon as it's opened, so it'll get
1351          * deleted even if the program dies
1352          */
1353         qfile = fopen(temp2, "r");
1354         unlink(temp2);
1355
1356         /* Display the quotable text with line numbers added */
1357         line = 0;
1358         if (fgets(buf, 128, qfile) == NULL) {
1359                 /* we're skipping a line here */
1360         }
1361         while (fgets(buf, 128, qfile) != NULL) {
1362                 scr_printf("%3d %s", ++line, buf);
1363         }
1364
1365         qstart = intprompt("Begin quoting at", 1, 1, line);
1366         qend = intprompt("  End quoting at", line, qstart, line);
1367
1368         rewind(qfile);
1369         line = 0;
1370         if (fgets(buf, 128, qfile) == NULL) {
1371                 /* we're skipping a line here */
1372         }
1373         tfile = fopen(temp, "w");
1374         while (fgets(buf, 128, qfile) != NULL) {
1375                 if ((++line >= qstart) && (line <= qend))
1376                         fprintf(tfile, " >%s", buf);
1377         }
1378         fprintf(tfile, " \n");
1379         fclose(qfile);
1380         fclose(tfile);
1381         chmod(temp, 0666);
1382 }
1383
1384
1385
1386 /*
1387  * List the URL's which were embedded in the previous message
1388  */
1389 void list_urls(CtdlIPC *ipc)
1390 {
1391         int i;
1392         char cmd[SIZ];
1393         int rv;
1394
1395         if (num_urls == 0) {
1396                 scr_printf("There were no URL's in the previous message.\n\n");
1397                 return;
1398         }
1399
1400         for (i = 0; i < num_urls; ++i) {
1401                 scr_printf("%3d %s\n", i + 1, urls[i]);
1402         }
1403
1404         if ((i = num_urls) != 1)
1405                 i = intprompt("Display which one", 1, 1, num_urls);
1406
1407         snprintf(cmd, sizeof cmd, rc_url_cmd, urls[i - 1]);
1408         rv = system(cmd);
1409         if (rv != 0) 
1410                 scr_printf("failed to '%s' by %d\n", cmd, rv);
1411         scr_printf("\n");
1412 }
1413
1414
1415 /*
1416  * Run image viewer in background
1417  */
1418 int do_image_view(const char *filename)
1419 {
1420         char cmd[SIZ];
1421         pid_t childpid;
1422
1423         snprintf(cmd, sizeof cmd, imagecmd, filename);
1424         childpid = fork();
1425         if (childpid < 0) {
1426                 unlink(filename);
1427                 return childpid;
1428         }
1429
1430         if (childpid == 0) {
1431                 int retcode;
1432                 pid_t grandchildpid;
1433
1434                 grandchildpid = fork();
1435                 if (grandchildpid < 0) {
1436                         return grandchildpid;
1437                 }
1438
1439                 if (grandchildpid == 0) {
1440                         int nullfd;
1441                         int outfd = -1;
1442                         int errfd = -1;
1443
1444                         nullfd = open("/dev/null", O_WRONLY);
1445                         if (nullfd > -1) {
1446                                 dup2(1, outfd);
1447                                 dup2(2, errfd);
1448                                 dup2(nullfd, 1);
1449                                 dup2(nullfd, 2);
1450                         }
1451                         retcode = system(cmd);
1452                         if (nullfd > -1) {
1453                                 dup2(outfd, 1);
1454                                 dup2(errfd, 2);
1455                                 close(nullfd);
1456                         }
1457                         unlink(filename);
1458                         exit(retcode);
1459                 }
1460
1461                 if (grandchildpid > 0) {
1462                         exit(0);
1463                 }
1464         }
1465
1466         if (childpid > 0) {
1467                 int retcode;
1468
1469                 waitpid(childpid, &retcode, 0);
1470                 return retcode;
1471         }
1472         
1473         return -1;
1474 }
1475
1476
1477 /*
1478  * View an image attached to a message
1479  */
1480 void image_view(CtdlIPC *ipc, unsigned long msg)
1481 {
1482         struct parts *ptr = last_message_parts;
1483         char part[SIZ];
1484         int found = 0;
1485
1486         /* Run through available parts */
1487         for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1488                 if ((!strcasecmp(ptr->disposition, "attachment")
1489                    || !strcasecmp(ptr->disposition, "inline"))
1490                    && !strncmp(ptr->mimetype, "image/", 6)) {
1491                         found++;
1492                         if (found == 1) {
1493                                 strcpy(part, ptr->number);
1494                         }
1495                 }
1496         }
1497
1498         while (found > 0) {
1499                 if (found > 1)
1500                         strprompt("View which part (0 when done)", part, SIZ-1);
1501                 found = -found;
1502                 for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1503                         if ((!strcasecmp(ptr->disposition, "attachment")
1504                            || !strcasecmp(ptr->disposition, "inline"))
1505                            && !strncmp(ptr->mimetype, "image/", 6)
1506                            && !strcasecmp(ptr->number, part)) {
1507                                 char tmp[PATH_MAX];
1508                                 char buf[SIZ];
1509                                 void *file = NULL; /* The downloaded file */
1510                                 int r;
1511         
1512                                 /* view image */
1513                                 found = -found;
1514                                 r = CtdlIPCAttachmentDownload(ipc, msg, ptr->number, &file, progress, buf);
1515                                 if (r / 100 != 2) {
1516                                         scr_printf("%s\n", buf);
1517                                 } else {
1518                                         size_t len;
1519         
1520                                         len = (size_t)extract_long(buf, 0);
1521                                         progress(ipc, len, len);
1522                                         scr_flush();
1523                                         CtdlMakeTempFileName(tmp, sizeof tmp);
1524                                         strcat(tmp, ptr->filename);
1525                                         save_buffer(file, len, tmp);
1526                                         free(file);
1527                                         do_image_view(tmp);
1528                                 }
1529                                 break;
1530                         }
1531                 }
1532                 if (found == 1)
1533                         break;
1534         }
1535 }
1536  
1537
1538 /*
1539  * Read the messages in the current room
1540  */
1541 void readmsgs(CtdlIPC *ipc,
1542         enum MessageList c,             /* see listing in citadel_ipc.h */
1543         enum MessageDirection rdir,     /* 1=Forward (-1)=Reverse */
1544         int q           /* Number of msgs to read (if c==3) */
1545 ) {
1546         int a, e, f, g, start;
1547         int savedpos;
1548         int hold_sw = 0;
1549         char arcflag = 0;
1550         char quotflag = 0;
1551         int hold_color = 0;
1552         char prtfile[PATH_MAX];
1553         char pagin;
1554         char cmd[SIZ];
1555         char targ[ROOMNAMELEN];
1556         char filename[PATH_MAX];
1557         char save_to[PATH_MAX];
1558         void *attachment = NULL;        /* Downloaded attachment */
1559         FILE *dest = NULL;              /* Alternate destination other than screen */
1560         int r;                          /* IPC response code */
1561         static int att_seq = 0;         /* Attachment download sequence number */
1562         int rv = 0;                     /* silence the stupid warn_unused_result warnings */
1563
1564         CtdlMakeTempFileName(prtfile, sizeof prtfile);
1565
1566         if (msg_arr) {
1567                 free(msg_arr);
1568                 msg_arr = NULL;
1569         }
1570         r = CtdlIPCGetMessages(ipc, c, q, NULL, &msg_arr, cmd);
1571         if (r / 100 != 1) {
1572                 scr_printf("%s\n", cmd);
1573         } else {
1574                 for (num_msgs = 0; msg_arr[num_msgs]; num_msgs++)
1575                         ;
1576         }
1577
1578         if (num_msgs == 0) {    /* TODO look at this later */
1579                 if (c == LastMessages) return;
1580                 scr_printf("*** There are no ");
1581                 if (c == NewMessages) scr_printf("new ");
1582                 if (c == OldMessages) scr_printf("old ");
1583                 scr_printf("messages in this room.\n");
1584                 return;
1585         }
1586
1587         /* this loop cycles through each message... */
1588         start = ((rdir == 1) ? 0 : (num_msgs - 1));
1589         for (a = start; ((a < num_msgs) && (a >= 0)); a = a + rdir) {
1590                 while (msg_arr[a] == 0L) {
1591                         a = a + rdir;
1592                         if ((a == num_msgs) || (a == (-1)))
1593                                 return;
1594                 }
1595
1596 RAGAIN:         pagin = ((arcflag == 0)
1597                          && (quotflag == 0)
1598                          && (userflags & US_PAGINATOR)) ? 1 : 0;
1599
1600                 /* If we're doing a quote, set the screenwidth to 72 */
1601                 if (quotflag) {
1602                         hold_sw = screenwidth;
1603                         screenwidth = 72;
1604                 }
1605
1606                 /* If printing or archiving, set the screenwidth to 80 */
1607                 if (arcflag) {
1608                         hold_sw = screenwidth;
1609                         screenwidth = 80;
1610                 }
1611
1612                 /* clear parts list */
1613                 free_parts(last_message_parts);
1614                 last_message_parts = NULL;
1615
1616                 /* now read the message... */
1617                 e = read_message(ipc, msg_arr[a], pagin, dest);
1618
1619                 /* ...and set the screenwidth back if we have to */
1620                 if ((quotflag) || (arcflag)) {
1621                         screenwidth = hold_sw;
1622                 }
1623 RMSGREAD:
1624                 highest_msg_read = msg_arr[a];
1625                 if (quotflag) {
1626                         fclose(dest);
1627                         dest = NULL;
1628                         quotflag = 0;
1629                         enable_color = hold_color;
1630                         process_quote();
1631                         e = 'r';
1632                         goto DONE_QUOTING;
1633                 }
1634                 if (arcflag) {
1635                         fclose(dest);
1636                         dest = NULL;
1637                         arcflag = 0;
1638                         enable_color = hold_color;
1639                         f = fork();
1640                         if (f == 0) {
1641                                 if (freopen(prtfile, "r", stdin) == NULL) {
1642                                         /* we probably should handle the error condition here */
1643                                 }
1644                                 stty_ctdl(SB_RESTORE);
1645                                 ka_system(printcmd);
1646                                 stty_ctdl(SB_NO_INTR);
1647                                 unlink(prtfile);
1648                                 exit(0);
1649                         }
1650                         if (f > 0)
1651                                 do {
1652                                         g = wait(NULL);
1653                                 } while ((g != f) && (g >= 0));
1654                         scr_printf("Message printed.\n");
1655                 }
1656                 if (e == SIGQUIT)
1657                         return;
1658                 if (((userflags & US_NOPROMPT) || (e == SIGINT))
1659                         && (((room_flags & QR_MAILBOX) == 0)
1660                         || (rc_force_mail_prompts == 0))) {
1661                         e = 'n';
1662                 } else {
1663                         color(DIM_WHITE);
1664                         scr_printf("(");
1665                         color(BRIGHT_WHITE);
1666                         scr_printf("%d", num_msgs - a - 1);
1667                         color(DIM_WHITE);
1668                         scr_printf(") ");
1669
1670                         keyopt("<B>ack <A>gain <R>eply reply<Q>uoted <N>ext <S>top ");
1671                         if (rc_url_cmd[0] && num_urls)
1672                                 keyopt("<U>RLview ");
1673                         if (has_images > 0 && !IsEmptyStr(imagecmd))
1674                                 keyopt("<I>mages ");
1675                         keyopt("<?>help -> ");
1676
1677                         do {
1678                                 e = (inkey() & 127);
1679                                 e = tolower(e);
1680 /* return key same as <N> */ if (e == 10)
1681                                         e = 'n';
1682 /* space key same as <N> */ if (e == 32)
1683                                         e = 'n';
1684 /* del/move for aides only */
1685                                     if (  (!is_room_aide)
1686                                        && ((room_flags & QR_MAILBOX) == 0)
1687                                        && ((room_flags2 & QR2_COLLABDEL) == 0)
1688                                        ) {
1689                                         if ((e == 'd') || (e == 'm'))
1690                                                 e = 0;
1691                                 }
1692 /* print only if available */
1693                                 if ((e == 'p') && (IsEmptyStr(printcmd)))
1694                                         e = 0;
1695 /* can't file if not allowed */
1696                                     if ((e == 'f')
1697                                         && (rc_allow_attachments == 0))
1698                                         e = 0;
1699 /* link only if browser avail*/
1700                                     if ((e == 'u')
1701                                         && (IsEmptyStr(rc_url_cmd)))
1702                                         e = 0;
1703                                 if ((e == 'i')
1704                                         && (IsEmptyStr(imagecmd) || !has_images))
1705                                         e = 0;
1706                         } while ((e != 'a') && (e != 'n') && (e != 's')
1707                                  && (e != 'd') && (e != 'm') && (e != 'p')
1708                                  && (e != 'q') && (e != 'b') && (e != 'h')
1709                                  && (e != 'r') && (e != 'f') && (e != '?')
1710                                  && (e != 'u') && (e != 'c') && (e != 'y')
1711                                  && (e != 'i') && (e != 'o') );
1712                         switch (e) {
1713                         case 's':
1714                                 scr_printf("Stop");
1715                                 break;
1716                         case 'a':
1717                                 scr_printf("Again");
1718                                 break;
1719                         case 'd':
1720                                 scr_printf("Delete");
1721                                 break;
1722                         case 'm':
1723                                 scr_printf("Move");
1724                                 break;
1725                         case 'c':
1726                                 scr_printf("Copy");
1727                                 break;
1728                         case 'n':
1729                                 scr_printf("Next");
1730                                 break;
1731                         case 'p':
1732                                 scr_printf("Print");
1733                                 break;
1734                         case 'q':
1735                                 scr_printf("reply Quoted");
1736                                 break;
1737                         case 'b':
1738                                 scr_printf("Back");
1739                                 break;
1740                         case 'h':
1741                                 scr_printf("Header");
1742                                 break;
1743                         case 'r':
1744                                 scr_printf("Reply");
1745                                 break;
1746                         case 'o':
1747                                 scr_printf("Open attachments");
1748                                 break;
1749                         case 'f':
1750                                 scr_printf("File");
1751                                 break;
1752                         case 'u':
1753                                 scr_printf("URL's");
1754                                 break;
1755                         case 'y':
1756                                 scr_printf("mY next");
1757                                 break;
1758                         case 'i':
1759                                 break;
1760                         case '?':
1761                                 scr_printf("? <help>");
1762                                 break;
1763                         }
1764                         if (userflags & US_DISAPPEAR || e == 'i')
1765                                 scr_printf("\r%79s\r", "");
1766                         else
1767                                 scr_printf("\n");
1768                 }
1769 DONE_QUOTING:   switch (e) {
1770                 case '?':
1771                         scr_printf("Options available here:\n"
1772                                 " ?  Help (prints this message)\n"
1773                                 " S  Stop reading immediately\n"
1774                                 " A  Again (repeats last message)\n"
1775                                 " N  Next (continue with next message)\n"
1776                                 " Y  My Next (continue with next message you authored)\n"
1777                                 " B  Back (go back to previous message)\n");
1778                         if (  (is_room_aide)
1779                            || (room_flags & QR_MAILBOX)
1780                            || (room_flags2 & QR2_COLLABDEL)
1781                         ) {
1782                                 scr_printf(" D  Delete this message\n"
1783                                         " M  Move message to another room\n");
1784                         }
1785                         scr_printf(" C  Copy message to another room\n");
1786                         if (!IsEmptyStr(printcmd))
1787                                 scr_printf(" P  Print this message\n");
1788                         scr_printf(
1789                                 " Q  Reply to this message, quoting portions of it\n"
1790                                 " H  Headers (display message headers only)\n");
1791                         if (is_mail)
1792                                 scr_printf(" R  Reply to this message\n");
1793                         if (rc_allow_attachments) {
1794                                 scr_printf(" O  (Open attachments)\n");
1795                                 scr_printf(" F  (save attachments to a File)\n");
1796                         }
1797                         if (!IsEmptyStr(rc_url_cmd))
1798                                 scr_printf(" U  (list URL's for display)\n");
1799                         if (!IsEmptyStr(imagecmd) && has_images > 0)
1800                                 scr_printf(" I  Image viewer\n");
1801                         scr_printf("\n");
1802                         goto RMSGREAD;
1803                 case 'p':
1804                         scr_flush();
1805                         dest = fopen(prtfile, "w");
1806                         arcflag = 1;
1807                         hold_color = enable_color;
1808                         enable_color = 0;
1809                         goto RAGAIN;
1810                 case 'q':
1811                         scr_flush();
1812                         dest = fopen(temp2, "w");
1813                         quotflag = 1;
1814                         hold_color = enable_color;
1815                         enable_color = 0;
1816                         goto RAGAIN;
1817                 case 's':
1818                         return;
1819                 case 'a':
1820                         goto RAGAIN;
1821                 case 'b':
1822                         a = a - (rdir * 2);
1823                         break;
1824                 case 'm':
1825                 case 'c':
1826                         newprompt("Enter target room: ",
1827                                   targ, ROOMNAMELEN - 1);
1828                         if (!IsEmptyStr(targ)) {
1829                                 r = CtdlIPCMoveMessage(ipc, (e == 'c' ? 1 : 0),
1830                                                        msg_arr[a], targ, cmd);
1831                                 scr_printf("%s\n", cmd);
1832                                 if (r / 100 == 2)
1833                                         msg_arr[a] = 0L;
1834                         } else {
1835                                 goto RMSGREAD;
1836                         }
1837                         if (r / 100 != 2)       /* r will be init'ed, FIXME */
1838                                 goto RMSGREAD;  /* the logic here sucks */
1839                         break;
1840                 case 'o':
1841                 case 'f':
1842                         newprompt("Which section? ", filename, ((sizeof filename) - 1));
1843                         r = CtdlIPCAttachmentDownload(ipc, msg_arr[a],
1844                                         filename, &attachment, progress, cmd);
1845                         if (r / 100 != 2) {
1846                                 scr_printf("%s\n", cmd);
1847                         } else {
1848                                 extract_token(filename, cmd, 2, '|', sizeof filename);
1849                                 /*
1850                                  * Part 1 won't have a filename; use the
1851                                  * subject of the message instead. IO
1852                                  */
1853                                 if (IsEmptyStr(filename)) {
1854                                         strcpy(filename, reply_subject);
1855                                 }
1856                                 if (e == 'o') {         /* open attachment */
1857                                         mkdir(tempdir, 0700);
1858                                         snprintf(save_to, sizeof save_to, "%s/%04x.%s",
1859                                                 tempdir,
1860                                                 ++att_seq,
1861                                                 filename);
1862                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1863                                         snprintf(cmd, sizeof cmd, rc_open_cmd, save_to);
1864                                         rv = system(cmd);
1865                                         if (rv != 0)
1866                                                 scr_printf("failed to save %s Reason %d\n", cmd, rv);
1867                                 }
1868                                 else {                  /* save attachment to disk */
1869                                         destination_directory(save_to, filename);
1870                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1871                                 }
1872                         }
1873                         if (attachment) {
1874                                 free(attachment);
1875                                 attachment = NULL;
1876                         }
1877                         goto RMSGREAD;
1878                 case 'd':
1879                         scr_printf("*** Delete this message? ");
1880                         if (yesno() == 1) {
1881                                 r = CtdlIPCDeleteMessage(ipc, msg_arr[a], cmd);
1882                                 scr_printf("%s\n", cmd);
1883                                 if (r / 100 == 2)
1884                                         msg_arr[a] = 0L;
1885                         } else {
1886                                 goto RMSGREAD;
1887                         }
1888                         break;
1889                 case 'h':
1890                         read_message(ipc, msg_arr[a], READ_HEADER, NULL);
1891                         goto RMSGREAD;
1892                 case 'r':
1893                         savedpos = num_msgs;
1894                         entmsg(ipc, 1, ((userflags & US_EXTEDIT) ? 2 : 0), 0);
1895                         num_msgs = savedpos;
1896                         goto RMSGREAD;
1897                 case 'u':
1898                         list_urls(ipc);
1899                         goto RMSGREAD;
1900                 case 'i':
1901                         image_view(ipc, msg_arr[a]);
1902                         goto RMSGREAD;
1903             case 'y':
1904           { /* hack hack hack */
1905             /* find the next message by me, stay here if we find nothing */
1906             int finda;
1907             int lasta = a;
1908             for (finda = (a + rdir); ((finda < num_msgs) && (finda >= 0)); finda += rdir)
1909               {
1910                 /* This is repetitively dumb, but that's what computers are for.
1911                    We have to load up messages until we find one by us */
1912                 char buf[SIZ];
1913                 int founda = 0;
1914                 struct ctdlipcmessage *msg = NULL;
1915                 
1916                 /* read the header so we can get 'from=' */
1917                 r = CtdlIPCGetSingleMessage(ipc, msg_arr[finda], 1, 0, &msg, buf);
1918                 if (!strncasecmp(msg->author, fullname, sizeof(fullname))) {
1919                         a = lasta; /* meesa current */
1920                         founda = 1;
1921                 }
1922
1923                 free(msg);
1924
1925                 if (founda)
1926                         break; /* for */
1927                 lasta = finda; /* keep one behind or we skip on the reentrance to the for */
1928               } /* for */
1929           } /* case 'y' */
1930       } /* switch */
1931         }                       /* end for loop */
1932 }                               /* end read routine */
1933
1934
1935
1936
1937 /*
1938  * View and edit a system message
1939  */
1940 void edit_system_message(CtdlIPC *ipc, char *which_message)
1941 {
1942         char desc[SIZ];
1943         char read_cmd[SIZ];
1944         char write_cmd[SIZ];
1945
1946         snprintf(desc, sizeof desc, "system message '%s'", which_message);
1947         snprintf(read_cmd, sizeof read_cmd, "MESG %s", which_message);
1948         snprintf(write_cmd, sizeof write_cmd, "EMSG %s", which_message);
1949         do_edit(ipc, desc, read_cmd, "NOOP", write_cmd);
1950 }
1951
1952
1953
1954
1955 /*
1956  * Loads the contents of a file into memory.  Caller must free the allocated
1957  * memory.
1958  */
1959 char *load_message_from_file(FILE *src)
1960 {
1961         size_t i;
1962         size_t got = 0;
1963         char *dest = NULL;
1964
1965         fseek(src, 0, SEEK_END);
1966         i = ftell(src);
1967         rewind(src);
1968
1969         dest = (char *)calloc(1, i + 1);
1970         if (!dest)
1971                 return NULL;
1972
1973         while (got < i) {
1974                 size_t g;
1975
1976                 g = fread(dest + got, 1, i - got, src);
1977                 got += g;
1978                 if (g < i - got) {
1979                         /* Interrupted system call, keep going */
1980                         if (errno == EINTR)
1981                                 continue;
1982                         /* At this point we have either EOF or error */
1983                         i = got;
1984                         break;
1985                 }
1986                 dest[i] = 0;
1987         }
1988
1989         return dest;
1990 }