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