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