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