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