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