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