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