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