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