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