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