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