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