adc1d13b6db0bebaa1e6e889c5d542dca7c2a556
[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 #ifndef HAVE_SNPRINTF
46 #include "snprintf.h"
47 #endif
48 #include "screen.h"
49
50 #define MAXWORDBUF SIZ
51 #define NO_REPLY_TO     "nobody ... xxxxxx"
52
53 char reply_to[SIZ];
54 char reply_subject[SIZ];
55
56 struct cittext {
57         struct cittext *next;
58         char text[MAXWORDBUF];
59 };
60
61 void stty_ctdl(int cmd);
62 int haschar(const char *st, int ch);
63 void ctdl_getline(char *string, int lim);
64 int file_checksum(char *filename);
65 void progress(CtdlIPC* ipc, unsigned long curr, unsigned long cmax);
66
67 unsigned long *msg_arr = NULL;
68 int msg_arr_size = 0;
69 int num_msgs;
70 char rc_alt_semantics;
71 extern char room_name[];
72 extern char tempdir[];
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("%3d %s", ++line, buf);
1280         }
1281         scr_printf("Begin quoting at [1] : ");
1282         ctdl_getline(buf, 4);
1283         qstart = (buf[0] == 0) ? (1) : atoi(buf);
1284         scr_printf("  End quoting at [%d] : ", line);
1285         ctdl_getline(buf, 4);
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         static int att_seq = 0;         /* Attachment download sequence number */
1476
1477         if (c < 0)
1478                 b = (num_msgs - 1);
1479         else
1480                 b = 0;
1481
1482         CtdlMakeTempFileName(prtfile, sizeof prtfile);
1483
1484         if (msg_arr) {
1485                 free(msg_arr);
1486                 msg_arr = NULL;
1487         }
1488         r = CtdlIPCGetMessages(ipc, c, q, NULL, &msg_arr, cmd);
1489         if (r / 100 != 1) {
1490                 scr_printf("%s\n", cmd);
1491         } else {
1492                 for (num_msgs = 0; msg_arr[num_msgs]; num_msgs++)
1493                         ;
1494         }
1495
1496         if (num_msgs == 0) {    /* TODO look at this later */
1497                 if (c == LastMessages) return;
1498                 scr_printf("*** There are no ");
1499                 if (c == NewMessages) scr_printf("new ");
1500                 if (c == OldMessages) scr_printf("old ");
1501                 scr_printf("messages in this room.\n");
1502                 return;
1503         }
1504
1505         lines_printed = 0;
1506
1507         /* this loop cycles through each message... */
1508         start = ((rdir == 1) ? 0 : (num_msgs - 1));
1509         for (a = start; ((a < num_msgs) && (a >= 0)); a = a + rdir) {
1510                 while (msg_arr[a] == 0L) {
1511                         a = a + rdir;
1512                         if ((a == num_msgs) || (a == (-1)))
1513                                 return;
1514                 }
1515
1516 RAGAIN:         pagin = ((arcflag == 0)
1517                          && (quotflag == 0)
1518                          && (userflags & US_PAGINATOR)) ? 1 : 0;
1519
1520                 /* If we're doing a quote, set the screenwidth to 72 */
1521                 if (quotflag) {
1522                         hold_sw = screenwidth;
1523                         screenwidth = 72;
1524                 }
1525
1526                 /* If printing or archiving, set the screenwidth to 80 */
1527                 if (arcflag) {
1528                         hold_sw = screenwidth;
1529                         screenwidth = 80;
1530                 }
1531
1532                 /* clear parts list */
1533                 free_parts(last_message_parts);
1534                 last_message_parts = NULL;
1535
1536                 /* now read the message... */
1537                 e = read_message(ipc, msg_arr[a], pagin, dest);
1538
1539                 /* ...and set the screenwidth back if we have to */
1540                 if ((quotflag) || (arcflag)) {
1541                         screenwidth = hold_sw;
1542                 }
1543 RMSGREAD:       scr_flush();
1544                 highest_msg_read = msg_arr[a];
1545                 if (quotflag) {
1546                         fclose(dest);
1547                         dest = NULL;
1548                         quotflag = 0;
1549                         enable_color = hold_color;
1550                         process_quote();
1551                 }
1552                 if (arcflag) {
1553                         fclose(dest);
1554                         dest = NULL;
1555                         arcflag = 0;
1556                         enable_color = hold_color;
1557                         f = fork();
1558                         if (f == 0) {
1559                                 freopen(prtfile, "r", stdin);
1560                                 screen_reset();
1561                                 stty_ctdl(SB_RESTORE);
1562                                 ka_system(printcmd);
1563                                 stty_ctdl(SB_NO_INTR);
1564                                 screen_set();
1565                                 unlink(prtfile);
1566                                 exit(0);
1567                         }
1568                         if (f > 0)
1569                                 do {
1570                                         g = wait(NULL);
1571                                 } while ((g != f) && (g >= 0));
1572                         scr_printf("Message printed.\n");
1573                 }
1574                 if (rc_alt_semantics && c == 1) {
1575                         char buf[SIZ];
1576
1577                         r = CtdlIPCSetMessageSeen(ipc, msg_arr[a], 1, buf);
1578                 }
1579                 if (e == SIGQUIT)
1580                         return;
1581                 if (((userflags & US_NOPROMPT) || (e == SIGINT))
1582                         && (((room_flags & QR_MAILBOX) == 0)
1583                         || (rc_force_mail_prompts == 0))) {
1584                         e = 'n';
1585                 } else {
1586                         color(DIM_WHITE);
1587                         scr_printf("(");
1588                         color(BRIGHT_WHITE);
1589                         scr_printf("%d", num_msgs - a - 1);
1590                         color(DIM_WHITE);
1591                         scr_printf(") ");
1592
1593                         keyopt("<B>ack <A>gain <Q>uote <R>eply <N>ext <S>top ");
1594                         if (rc_url_cmd[0] && num_urls)
1595                                 keyopt("<U>RLview ");
1596                         if (has_images > 0 && !IsEmptyStr(imagecmd))
1597                                 keyopt("<I>mages ");
1598                         keyopt("<?>help -> ");
1599
1600                         do {
1601                                 lines_printed = 2;
1602                                 e = (inkey() & 127);
1603                                 e = tolower(e);
1604 /* return key same as <N> */ if (e == 10)
1605                                         e = 'n';
1606 /* space key same as <N> */ if (e == 32)
1607                                         e = 'n';
1608 /* del/move for aides only */
1609                                     if (  (!is_room_aide)
1610                                        && ((room_flags & QR_MAILBOX) == 0)
1611                                        && ((room_flags2 & QR2_COLLABDEL) == 0)
1612                                        ) {
1613                                         if ((e == 'd') || (e == 'm'))
1614                                                 e = 0;
1615                                 }
1616 /* print only if available */
1617                                 if ((e == 'p') && (IsEmptyStr(printcmd)))
1618                                         e = 0;
1619 /* can't file if not allowed */
1620                                     if ((e == 'f')
1621                                         && (rc_allow_attachments == 0))
1622                                         e = 0;
1623 /* link only if browser avail*/
1624                                     if ((e == 'u')
1625                                         && (IsEmptyStr(rc_url_cmd)))
1626                                         e = 0;
1627                                 if ((e == 'i')
1628                                         && (IsEmptyStr(imagecmd) || !has_images))
1629                                         e = 0;
1630                         } while ((e != 'a') && (e != 'n') && (e != 's')
1631                                  && (e != 'd') && (e != 'm') && (e != 'p')
1632                                  && (e != 'q') && (e != 'b') && (e != 'h')
1633                                  && (e != 'r') && (e != 'f') && (e != '?')
1634                                  && (e != 'u') && (e != 'c') && (e != 'y')
1635                                  && (e != 'i') && (e != 'o') );
1636                         switch (e) {
1637                         case 's':
1638                                 scr_printf("Stop");
1639                                 break;
1640                         case 'a':
1641                                 scr_printf("Again");
1642                                 break;
1643                         case 'd':
1644                                 scr_printf("Delete");
1645                                 break;
1646                         case 'm':
1647                                 scr_printf("Move");
1648                                 break;
1649                         case 'c':
1650                                 scr_printf("Copy");
1651                                 break;
1652                         case 'n':
1653                                 scr_printf("Next");
1654                                 break;
1655                         case 'p':
1656                                 scr_printf("Print");
1657                                 break;
1658                         case 'q':
1659                                 scr_printf("Quote");
1660                                 break;
1661                         case 'b':
1662                                 scr_printf("Back");
1663                                 break;
1664                         case 'h':
1665                                 scr_printf("Header");
1666                                 break;
1667                         case 'r':
1668                                 scr_printf("Reply");
1669                                 break;
1670                         case 'o':
1671                                 scr_printf("Open attachments");
1672                                 break;
1673                         case 'f':
1674                                 scr_printf("File");
1675                                 break;
1676                         case 'u':
1677                                 scr_printf("URL's");
1678                                 break;
1679                         case 'y':
1680                                 scr_printf("mY next");
1681                                 break;
1682                         case 'i':
1683                                 break;
1684                         case '?':
1685                                 scr_printf("? <help>");
1686                                 break;
1687                         }
1688                         if (userflags & US_DISAPPEAR || e == 'i')
1689                                 scr_printf("\r%79s\r", "");
1690                         else
1691                                 scr_printf("\n");
1692                         scr_flush();
1693                 }
1694                 switch (e) {
1695                 case '?':
1696                         scr_printf("Options available here:\n"
1697                                 " ?  Help (prints this message)\n"
1698                                 " S  Stop reading immediately\n"
1699                                 " A  Again (repeats last message)\n"
1700                                 " N  Next (continue with next message)\n"
1701                                 " Y  My Next (continue with next message you authored)\n"
1702                                 " B  Back (go back to previous message)\n");
1703                         if (  (is_room_aide)
1704                            || (room_flags & QR_MAILBOX)
1705                            || (room_flags2 & QR2_COLLABDEL)
1706                         ) {
1707                                 scr_printf(" D  Delete this message\n"
1708                                         " M  Move message to another room\n");
1709                         }
1710                         scr_printf(" C  Copy message to another room\n");
1711                         if (!IsEmptyStr(printcmd))
1712                                 scr_printf(" P  Print this message\n");
1713                         scr_printf(
1714                                 " Q  Quote portions of this message for your next post\n"
1715                                 " H  Headers (display message headers only)\n");
1716                         if (is_mail)
1717                                 scr_printf(" R  Reply to this message\n");
1718                         if (rc_allow_attachments) {
1719                                 scr_printf(" O  (Open attachments)\n");
1720                                 scr_printf(" F  (save attachments to a File)\n");
1721                         }
1722                         if (!IsEmptyStr(rc_url_cmd))
1723                                 scr_printf(" U  (list URL's for display)\n");
1724                         if (!IsEmptyStr(imagecmd) && has_images > 0)
1725                                 scr_printf(" I  Image viewer\n");
1726                         scr_printf("\n");
1727                         goto RMSGREAD;
1728                 case 'p':
1729                         scr_flush();
1730                         dest = fopen(prtfile, "w");
1731                         arcflag = 1;
1732                         hold_color = enable_color;
1733                         enable_color = 0;
1734                         goto RAGAIN;
1735                 case 'q':
1736                         scr_flush();
1737                         dest = fopen(temp2, "w");
1738                         quotflag = 1;
1739                         hold_color = enable_color;
1740                         enable_color = 0;
1741                         goto RAGAIN;
1742                 case 's':
1743                         return;
1744                 case 'a':
1745                         goto RAGAIN;
1746                 case 'b':
1747                         a = a - (rdir * 2);
1748                         break;
1749                 case 'm':
1750                 case 'c':
1751                         newprompt("Enter target room: ",
1752                                   targ, ROOMNAMELEN - 1);
1753                         if (!IsEmptyStr(targ)) {
1754                                 r = CtdlIPCMoveMessage(ipc, (e == 'c' ? 1 : 0),
1755                                                        msg_arr[a], targ, cmd);
1756                                 scr_printf("%s\n", cmd);
1757                                 if (r / 100 == 2)
1758                                         msg_arr[a] = 0L;
1759                         } else {
1760                                 goto RMSGREAD;
1761                         }
1762                         if (r / 100 != 2)       /* r will be init'ed, FIXME */
1763                                 goto RMSGREAD;  /* the logic here sucks */
1764                         break;
1765                 case 'o':
1766                 case 'f':
1767                         newprompt("Which section? ", filename, ((sizeof filename) - 1));
1768                         r = CtdlIPCAttachmentDownload(ipc, msg_arr[a],
1769                                         filename, &attachment, progress, cmd);
1770                         if (r / 100 != 2) {
1771                                 scr_printf("%s\n", cmd);
1772                         } else {
1773                                 extract_token(filename, cmd, 2, '|', sizeof filename);
1774                                 /*
1775                                  * Part 1 won't have a filename; use the
1776                                  * subject of the message instead. IO
1777                                  */
1778                                 if (IsEmptyStr(filename)) {
1779                                         strcpy(filename, reply_subject);
1780                                 }
1781                                 if (e == 'o') {         /* open attachment */
1782                                         mkdir(tempdir, 0700);
1783                                         snprintf(save_to, sizeof save_to, "%s/%04x.%s",
1784                                                 tempdir,
1785                                                 ++att_seq,
1786                                                 filename);
1787                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1788                                         snprintf(cmd, sizeof cmd, rc_open_cmd, save_to);
1789                                         system(cmd);
1790                                 }
1791                                 else {                  /* save attachment to disk */
1792                                         destination_directory(save_to, filename);
1793                                         save_buffer(attachment, extract_unsigned_long(cmd, 0), save_to);
1794                                 }
1795                         }
1796                         if (attachment) {
1797                                 free(attachment);
1798                                 attachment = NULL;
1799                         }
1800                         goto RMSGREAD;
1801                 case 'd':
1802                         scr_printf("*** Delete this message? ");
1803                         if (yesno() == 1) {
1804                                 r = CtdlIPCDeleteMessage(ipc, msg_arr[a], cmd);
1805                                 scr_printf("%s\n", cmd);
1806                                 if (r / 100 == 2)
1807                                         msg_arr[a] = 0L;
1808                         } else {
1809                                 goto RMSGREAD;
1810                         }
1811                         break;
1812                 case 'h':
1813                         read_message(ipc, msg_arr[a], READ_HEADER, NULL);
1814                         goto RMSGREAD;
1815                 case 'r':
1816                         savedpos = num_msgs;
1817                         entmsg(ipc, 1, ((userflags & US_EXTEDIT) ? 2 : 0), 0);
1818                         num_msgs = savedpos;
1819                         goto RMSGREAD;
1820                 case 'u':
1821                         list_urls(ipc);
1822                         goto RMSGREAD;
1823                 case 'i':
1824                         image_view(ipc, msg_arr[a]);
1825                         goto RMSGREAD;
1826             case 'y':
1827           { /* hack hack hack */
1828             /* find the next message by me, stay here if we find nothing */
1829             int finda;
1830             int lasta = a;
1831             for (finda = (a + rdir); ((finda < num_msgs) && (finda >= 0)); finda += rdir)
1832               {
1833                 /* This is repetitively dumb, but that's what computers are for.
1834                    We have to load up messages until we find one by us */
1835                 char buf[SIZ];
1836                 int founda = 0;
1837                 struct ctdlipcmessage *msg = NULL;
1838                 
1839                 /* read the header so we can get 'from=' */
1840                 r = CtdlIPCGetSingleMessage(ipc, msg_arr[finda], 1, 0, &msg, buf);
1841                 if (!strncasecmp(msg->author, fullname, sizeof(fullname))) {
1842                         a = lasta; /* meesa current */
1843                         founda = 1;
1844                 }
1845
1846                 free(msg);
1847
1848                 if (founda)
1849                         break; /* for */
1850                 lasta = finda; /* keep one behind or we skip on the reentrance to the for */
1851               } /* for */
1852           } /* case 'y' */
1853       } /* switch */
1854         }                       /* end for loop */
1855 }                               /* end read routine */
1856
1857
1858
1859
1860 /*
1861  * View and edit a system message
1862  */
1863 void edit_system_message(CtdlIPC *ipc, char *which_message)
1864 {
1865         char desc[SIZ];
1866         char read_cmd[SIZ];
1867         char write_cmd[SIZ];
1868
1869         snprintf(desc, sizeof desc, "system message '%s'", which_message);
1870         snprintf(read_cmd, sizeof read_cmd, "MESG %s", which_message);
1871         snprintf(write_cmd, sizeof write_cmd, "EMSG %s", which_message);
1872         do_edit(ipc, desc, read_cmd, "NOOP", write_cmd);
1873 }
1874
1875
1876
1877
1878 /*
1879  * Verify the message base
1880  */
1881 void check_message_base(CtdlIPC *ipc)
1882 {
1883         char buf[SIZ];
1884         char *transcript = NULL;
1885         int r;          /* IPC response code */
1886
1887         scr_printf
1888             ("Please read the documentation before running this command.\n"
1889             "Having done so, do you still want to check the message base? ");
1890         if (yesno() == 0)
1891                 return;
1892
1893         r = CtdlIPCMessageBaseCheck(ipc, &transcript, buf);
1894         if (r / 100 != 1) {
1895                 scr_printf("%s\n", buf);
1896                 return;
1897         }
1898
1899         while (transcript && !IsEmptyStr(transcript)) {
1900                 lines_printed = 1;
1901                 extract_token(buf, transcript, 0, '\n', sizeof buf);
1902                 remove_token(transcript, 0, '\n');
1903                 pprintf("%s\n", buf);
1904         }
1905         if (transcript) free(transcript);
1906         return;
1907 }
1908
1909
1910 /*
1911  * Loads the contents of a file into memory.  Caller must free the allocated
1912  * memory.
1913  */
1914 char *load_message_from_file(FILE *src)
1915 {
1916         size_t i;
1917         size_t got = 0;
1918         char *dest = NULL;
1919
1920         fseek(src, 0, SEEK_END);
1921         i = ftell(src);
1922         rewind(src);
1923
1924         dest = (char *)calloc(1, i + 1);
1925         if (!dest)
1926                 return NULL;
1927
1928         while (got < i) {
1929                 size_t g;
1930
1931                 g = fread(dest + got, 1, i - got, src);
1932                 got += g;
1933                 if (g < i - got) {
1934                         /* Interrupted system call, keep going */
1935                         if (errno == EINTR)
1936                                 continue;
1937                         /* At this point we have either EOF or error */
1938                         i = got;
1939                         break;
1940                 }
1941                 dest[i] = 0;
1942         }
1943
1944         return dest;
1945 }