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