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