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