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