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