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