]> code.citadel.org Git - citadel.git/blob - citadel/messages.c
* Fork image viewer process in background (works now); suppress
[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
362 /*
363  * Free the struct parts
364  */
365 void free_parts(struct parts *p)
366 {
367         struct parts *a_part = p;
368
369         while (a_part) {
370                 struct parts *q;
371
372                 q = a_part;
373                 a_part = a_part->next;
374                 free(q);
375         }
376 }
377
378
379 /*
380  * Read a message from the server
381  */
382 int read_message(CtdlIPC *ipc,
383         long num,   /* message number */
384         int pagin, /* 0 = normal read, 1 = read with pagination, 2 = header */
385         FILE *dest) /* Destination file, NULL for screen */
386 {
387         char buf[SIZ];
388         char now[SIZ];
389         int format_type = 0;
390         int fr = 0;
391         int nhdr = 0;
392         struct ctdlipcmessage *message = NULL;
393         int r;                          /* IPC response code */
394         char *converted_text = NULL;
395         char *lineptr;
396         char *nextline;
397         char *searchptr;
398         int i;
399         char ch;
400         int linelen;
401         int final_line_is_blank = 0;
402
403         has_images = 0;
404
405         sigcaught = 0;
406         sttybbs(1);
407
408         strcpy(reply_to, NO_REPLY_TO);
409         strcpy(reply_subject, "");
410
411         r = CtdlIPCGetSingleMessage(ipc, num, (pagin == READ_HEADER ? 1 : 0),
412                                 (can_do_msg4 ? 4 : 0),
413                                 &message, buf);
414         if (r / 100 != 1) {
415                 err_printf("*** msg #%ld: %d %s\n", num, r, buf);
416                 ++lines_printed;
417                 lines_printed =
418                     checkpagin(lines_printed, pagin, screenheight);
419                 sttybbs(0);
420                 return (0);
421         }
422
423         if (dest) {
424                 fprintf(dest, "\n ");
425         } else {
426                 scr_printf("\n");
427                 ++lines_printed;
428                 lines_printed = checkpagin(lines_printed, pagin, screenheight);
429                 if (pagin != 2)
430                         scr_printf(" ");
431         }
432         if (pagin == 1 && !dest) {
433                 color(BRIGHT_CYAN);
434         }
435
436         /* View headers only */
437         if (pagin == 2) {
438                 pprintf("nhdr=%s\nfrom=%s\ntype=%d\nmsgn=%s\n",
439                                 message->nhdr ? "yes" : "no",
440                                 message->author, message->type,
441                                 message->msgid);
442                 if (strlen(message->subject)) {
443                         pprintf("subj=%s\n", message->subject);
444                 }
445                 if (strlen(message->email)) {
446                         pprintf("rfca=%s\n", message->email);
447                 }
448                 pprintf("hnod=%s\nroom=%s\nnode=%s\ntime=%s",
449                                 message->hnod, message->room,
450                                 message->node, 
451                                 asctime(localtime(&message->time)));
452                 if (strlen(message->recipient)) {
453                         pprintf("rcpt=%s\n", message->recipient);
454                 }
455                 if (message->attachments) {
456                         struct parts *ptr;
457
458                         for (ptr = message->attachments; ptr; ptr = ptr->next) {
459                                 pprintf("part=%s|%s|%s|%s|%s|%ld\n",
460                                         ptr->name, ptr->filename, ptr->number,
461                                         ptr->disposition, ptr->mimetype,
462                                         ptr->length);
463                         }
464                 }
465                 pprintf("\n");
466                 sttybbs(0);
467                 return (0);
468         }
469
470         if (rc_display_message_numbers) {
471                 if (dest) {
472                         fprintf(dest, "[#%s] ", message->msgid);
473                 } else {
474                         color(DIM_WHITE);
475                         scr_printf("[");
476                         color(BRIGHT_WHITE);
477                         scr_printf("#%s", message->msgid);
478                         color(DIM_WHITE);
479                         scr_printf("] ");
480                 }
481         }
482         if (nhdr == 1 && !is_room_aide) {
483                 if (dest) {
484                         fprintf(dest, " ****");
485                 } else {
486                         scr_printf(" ****");
487                 }
488         } else {
489                 fmt_date(now, sizeof now, message->time, 0);
490                 if (dest) {
491                         fprintf(dest, "%s from %s ", now, message->author);
492                         if (strlen(message->email)) {
493                                 fprintf(dest, "<%s> ", message->email);
494                         }
495                 } else {
496                         color(BRIGHT_CYAN);
497                         scr_printf("%s ", now);
498                         color(DIM_WHITE);
499                         scr_printf("from ");
500                         color(BRIGHT_CYAN);
501                         scr_printf("%s ", message->author);
502                         if (strlen(message->email)) {
503                                 color(DIM_WHITE);
504                                 scr_printf("<");
505                                 color(BRIGHT_BLUE);
506                                 scr_printf("%s", message->email);
507                                         color(DIM_WHITE);
508                                 scr_printf("> ");
509                         }
510                 }
511                 if (strlen(message->node)) {
512                         if ((room_flags & QR_NETWORK)
513                             || ((strcasecmp(message->node, serv_info.serv_nodename)
514                              && (strcasecmp(message->node, serv_info.serv_fqdn))))) {
515                                 if (strlen(message->email) == 0) {
516                                         if (dest) {
517                                                 fprintf(dest, "@%s ", message->node);
518                                         } else {
519                                                 color(DIM_WHITE);
520                                                 scr_printf("@");
521                                                 color(BRIGHT_YELLOW);
522                                                 scr_printf("%s ", message->node);
523                                         }
524                                 }
525                         }
526                 }
527                 if (strcasecmp(message->hnod, serv_info.serv_humannode)
528                     && (strlen(message->hnod)) && (!strlen(message->email))) {
529                         if (dest) {
530                                 fprintf(dest, "(%s) ", message->hnod);
531                         } else {
532                                 color(DIM_WHITE);
533                                 scr_printf("(");
534                                 color(BRIGHT_WHITE);
535                                 scr_printf("%s", message->hnod);
536                                 color(DIM_WHITE);
537                                 scr_printf(") ");
538                         }
539                 }
540                 if (strcasecmp(message->room, room_name) && (strlen(message->email) == 0)) {
541                         if (dest) {
542                                 fprintf(dest, "in %s> ", message->room);
543                         } else {
544                                 color(DIM_WHITE);
545                                 scr_printf("in ");
546                                 color(BRIGHT_MAGENTA);
547                                 scr_printf("%s> ", message->room);
548                         }
549                 }
550                 if (strlen(message->recipient)) {
551                         if (dest) {
552                                 fprintf(dest, "to %s ", message->recipient);
553                         } else {
554                                 color(DIM_WHITE);
555                                 scr_printf("to ");
556                                 color(BRIGHT_CYAN);
557                                 scr_printf("%s ", message->recipient);
558                         }
559                 }
560         }
561         
562         if (dest) {
563                 fprintf(dest, "\n");
564         } else {
565                 scr_printf("\n");
566         }
567
568         /* Set the reply-to address to an Internet e-mail address if possible
569          */
570         if (message->email != NULL) if (strlen(message->email) > 0) {
571                 safestrncpy(reply_to, message->email, sizeof reply_to);
572         }
573
574         /* But if we can't do that, set it to a Citadel address.
575          */
576         if (!strcmp(reply_to, NO_REPLY_TO)) {
577                 snprintf(reply_to, sizeof(reply_to), "%s @ %s",
578                          message->author, message->node);
579         }
580
581         if (!dest) {
582                 ++lines_printed;
583                 lines_printed = checkpagin(lines_printed, pagin, screenheight);
584         }
585
586         if (message->subject != NULL) {
587                 safestrncpy(reply_subject, message->subject,
588                                                 sizeof reply_subject);
589                 if (strlen(message->subject) > 0) {
590                         if (dest) {
591                                 fprintf(dest, "Subject: %s\n",
592                                                         message->subject);
593                         } else {
594                                 color(DIM_WHITE);
595                                 scr_printf("Subject: ");
596                                 color(BRIGHT_CYAN);
597                                 scr_printf("%s\n", message->subject);
598                                 ++lines_printed;
599                                 lines_printed = checkpagin(lines_printed,
600                                                 pagin, screenheight);
601                         }
602                 }
603         }
604
605         if (pagin == 1 && !dest) {
606                 color(BRIGHT_WHITE);
607         }
608
609         /******* end of header output, start of message text output *******/
610
611         /*
612          * Convert HTML to plain text, formatting for the actual width
613          * of the client screen.
614          */
615         if (!strcasecmp(message->content_type, "text/html")) {
616                 converted_text = html_to_ascii(message->text, screenwidth, 0);
617                 if (converted_text != NULL) {
618                         free(message->text);
619                         message->text = converted_text;
620                         format_type = 1;
621                 }
622         }
623
624         /* Text/plain is a different type */
625         if (!strcasecmp(message->content_type, "text/plain")) {
626                 format_type = 1;
627         }
628
629         /* Extract URL's */
630         num_urls = 0;   /* Start with a clean slate */
631         searchptr = message->text;
632         while ( (searchptr != NULL) && (num_urls < MAXURLS) ) {
633                 searchptr = strstr(searchptr, "http://");
634                 if (searchptr != NULL) {
635                         safestrncpy(urls[num_urls], searchptr, sizeof(urls[num_urls]));
636                         for (i = 0; i < strlen(urls[num_urls]); i++) {
637                                 ch = urls[num_urls][i];
638                                 if (ch == '>' || ch == '\"' || ch == ')' ||
639                                     ch == ' ' || ch == '\n') {
640                                         urls[num_urls][i] = 0;
641                                         break;
642                                 }
643                         }
644                         num_urls++;
645                         ++searchptr;
646                 }
647         }
648
649         /*
650          * Here we go
651          */
652         if (format_type == 0) {
653                 fr = fmout(screenwidth, NULL, message->text, dest,
654                            ((pagin == 1) ? 1 : 0), screenheight, (-1), 1);
655         } else {
656                 /* renderer for text/plain */
657
658                 lineptr = message->text;
659
660                 do {
661                         nextline = strchr(lineptr, '\n');
662                         if (nextline != NULL) {
663                                 *nextline = 0;
664                                 ++nextline;
665                                 if (*nextline == 0) nextline = NULL;
666                         }
667
668                         if (sigcaught == 0) {
669                                 linelen = strlen(lineptr);
670                                 if (lineptr[linelen-1] == '\r') {
671                                         lineptr[--linelen] = 0;
672                                 }
673                                 if (dest) {
674                                         fprintf(dest, "%s\n", lineptr);
675                                 } else {
676                                         scr_printf("%s\n", lineptr);
677                                         lines_printed = lines_printed + 1 +
678                                             (linelen / screenwidth);
679                                         lines_printed =
680                                             checkpagin(lines_printed, pagin,
681                                                        screenheight);
682                                 }
683                         }
684                         if (lineptr[0] == 0) final_line_is_blank = 1;
685                         else final_line_is_blank = 0;
686                         lineptr = nextline;
687                 } while (nextline);
688                 fr = sigcaught;
689         }
690         if (!final_line_is_blank) {
691                 if (dest) {
692                         fprintf(dest, "\n");
693                 }
694                 else {
695                         scr_printf("\n");
696                         ++lines_printed;
697                         lines_printed = checkpagin(lines_printed, pagin, screenheight);
698                 }
699         }
700
701         /* Enumerate any attachments */
702         if ( (pagin == 1) && (can_do_msg4) && (message->attachments) ) {
703                 struct parts *ptr;
704
705                 for (ptr = message->attachments; ptr; ptr = ptr->next) {
706                         if ( (!strcasecmp(ptr->disposition, "attachment"))
707                            || (!strcasecmp(ptr->disposition, "inline"))) {
708                                 color(DIM_WHITE);
709                                 pprintf("Part ");
710                                 color(BRIGHT_MAGENTA);
711                                 pprintf("%s", ptr->number);
712                                 color(DIM_WHITE);
713                                 pprintf(": ");
714                                 color(BRIGHT_CYAN);
715                                 pprintf("%s", ptr->filename);
716                                 color(DIM_WHITE);
717                                 pprintf(" (%s, %ld bytes)\n", ptr->mimetype, ptr->length);
718                                 if (!strncmp(ptr->mimetype, "image/", 6))
719                                         has_images++;
720                         }
721                 }
722         }
723
724         /* Save the attachments info for later */
725         last_message_parts = message->attachments;
726
727         /* Now we're done */
728         free(message->text);
729         free(message);
730
731         if (pagin == 1 && !dest)
732                 color(DIM_WHITE);
733         sttybbs(0);
734         return (fr);
735 }
736
737 /*
738  * replace string function for the built-in editor
739  */
740 void replace_string(char *filename, long int startpos)
741 {
742         char buf[512];
743         char srch_str[128];
744         char rplc_str[128];
745         FILE *fp;
746         int a;
747         long rpos, wpos;
748         char *ptr;
749         int substitutions = 0;
750         long msglen = 0L;
751
752         scr_printf("Enter text to be replaced:\n: ");
753         getline(srch_str, (sizeof(srch_str)-1) );
754         if (strlen(srch_str) == 0)
755                 return;
756
757         scr_printf("Enter text to replace it with:\n: ");
758         getline(rplc_str, (sizeof(rplc_str)-1) );
759
760         fp = fopen(filename, "r+");
761         if (fp == NULL)
762                 return;
763
764         wpos = startpos;
765         fseek(fp, startpos, 0);
766         strcpy(buf, "");
767         while (a = getc(fp), a > 0) {
768                 ++msglen;
769                 buf[strlen(buf) + 1] = 0;
770                 buf[strlen(buf)] = a;
771                 if (strlen(buf) >= strlen(srch_str)) {
772                         ptr = (&buf[strlen(buf) - strlen(srch_str)]);
773                         if (!strncmp(ptr, srch_str, strlen(srch_str))) {
774                                 strcpy(ptr, rplc_str);
775                                 ++substitutions;
776                         }
777                 }
778                 if (strlen(buf) > 384) {
779                         rpos = ftell(fp);
780                         fseek(fp, wpos, 0);
781                         fwrite((char *) buf, 128, 1, fp);
782                         strcpy(buf, &buf[128]);
783                         wpos = ftell(fp);
784                         fseek(fp, rpos, 0);
785                 }
786         }
787         fseek(fp, wpos, 0);
788         if (strlen(buf) > 0)
789                 fwrite((char *) buf, strlen(buf), 1, fp);
790         wpos = ftell(fp);
791         fclose(fp);
792         truncate(filename, wpos);
793         scr_printf("<R>eplace made %d substitution(s).\n\n", substitutions);
794 }
795
796 /*
797  * Function to begin composing a new message
798  */
799 int client_make_message(CtdlIPC *ipc,
800                 char *filename,         /* temporary file name */
801                 char *recipient,        /* NULL if it's not mail */
802                 int is_anonymous,
803                 int format_type,
804                 int mode,
805                 char *subject)          /* buffer to store subject line */
806 {
807         FILE *fp;
808         int a, b, e_ex_code;
809         long beg;
810         char datestr[SIZ];
811         char header[SIZ];
812         char *editor_path = NULL;
813         int cksum = 0;
814
815         if (mode >= 2)
816         {
817                 if((mode-2) < MAX_EDITORS && strlen(editor_paths[mode-2]) > 0) {
818                         editor_path = editor_paths[mode-2];
819                 } else if (strlen(editor_paths[0]) > 0) {
820                         editor_path = editor_paths[0];
821                 } else {
822                         err_printf
823                             ("*** No editor available, using built-in editor\n");
824                         mode = 0;
825                 }
826         }
827
828         fmt_date(datestr, sizeof datestr, time(NULL), 0);
829         header[0] = 0;
830
831         if (room_flags & QR_ANONONLY && !recipient) {
832                 snprintf(header, sizeof header, " ****");
833         }
834         else {
835                 snprintf(header, sizeof header,
836                         " %s from %s",
837                         datestr,
838                         (is_anonymous ? "[anonymous]" : fullname)
839                         );
840                 if (strlen(recipient) > 0) {
841                         size_t tmp = strlen(header);
842                         snprintf(&header[tmp], sizeof header - tmp,
843                                 " to %s", recipient);
844                 }
845         }
846         scr_printf("%s\n", header);
847         if (subject != NULL) if (strlen(subject) > 0) {
848                 scr_printf("Subject: %s\n", subject);
849         }
850
851         beg = 0L;
852
853         if (mode == 1) {
854                 scr_printf("(Press ctrl-d when finished)\n");
855         }
856
857         if (mode == 0) {
858                 fp = fopen(filename, "r");
859                 if (fp != NULL) {
860                         fmout(screenwidth, fp, NULL, NULL, 0, screenheight, 0, 0);
861                         beg = ftell(fp);
862                         fclose(fp);
863                 } else {
864                         fp = fopen(filename, "w");
865                         if (fp == NULL) {
866                                 err_printf("*** Error opening temp file!\n"
867                                         "    %s: %s\n",
868                                         filename, strerror(errno));
869                         return(1);
870                         }
871                         fclose(fp);
872                 }
873         }
874
875 ME1:    switch (mode) {
876
877         case 0:
878                 fp = fopen(filename, "r+");
879                 if (fp == NULL) {
880                         err_printf("*** Error opening temp file!\n"
881                                 "    %s: %s\n",
882                                 filename, strerror(errno));
883                         return(1);
884                 }
885                 citedit(ipc, fp);
886                 fclose(fp);
887                 goto MECR;
888
889         case 1:
890                 fp = fopen(filename, "a");
891                 if (fp == NULL) {
892                         err_printf("*** Error opening temp file!\n"
893                                 "    %s: %s\n",
894                                 filename, strerror(errno));
895                         return(1);
896                 }
897                 do {
898                         a = inkey();
899                         if (a == 255)
900                                 a = 32;
901                         if (a == 13)
902                                 a = 10;
903                         if (a != 4) {
904                                 putc(a, fp);
905                                 scr_putc(a);
906                         }
907                         if (a == 10)
908                                 scr_putc(10);
909                 } while (a != 4);
910                 fclose(fp);
911                 break;
912
913         case 2:
914         default:        /* allow 2+ modes */
915                 e_ex_code = 1;  /* start with a failed exit code */
916                 editor_pid = fork();
917                 cksum = file_checksum(filename);
918                 screen_reset();
919                 sttybbs(SB_RESTORE);
920                 if (editor_pid == 0) {
921                         char tmp[SIZ];
922
923                         chmod(filename, 0600);
924                         snprintf(tmp, sizeof tmp, "WINDOW_TITLE=%s", header);
925                         putenv(tmp);
926                         execlp(editor_path, editor_path, filename, NULL);
927                         exit(1);
928                 }
929                 if (editor_pid > 0)
930                         do {
931                                 e_ex_code = 0;
932                                 b = ka_wait(&e_ex_code);
933                         } while ((b != editor_pid) && (b >= 0));
934                 editor_pid = (-1);
935                 sttybbs(0);
936                 screen_set();
937                 break;
938         }
939
940 MECR:   if (mode >= 2) {
941                 if (file_checksum(filename) == cksum) {
942                         err_printf("*** Aborted message.\n");
943                         e_ex_code = 1;
944                 }
945                 if (e_ex_code == 0)
946                         goto MEFIN;
947                 goto MEABT2;
948         }
949
950         b = keymenu("Entry command (? for options)",
951                     "<A>bort|<C>ontinue|<S>ave message|<P>rint formatted|"
952                     "add s<U>bject|"
953                     "<R>eplace string|<H>old message");
954
955         if (b == 'a')
956                 goto MEABT;
957         if (b == 'c')
958                 goto ME1;
959         if (b == 's')
960                 goto MEFIN;
961         if (b == 'p') {
962                 scr_printf(" %s from %s", datestr, fullname);
963                 if (strlen(recipient) > 0)
964                         scr_printf(" to %s", recipient);
965                 scr_printf("\n");
966                 if (subject != NULL) if (strlen(subject) > 0) {
967                         scr_printf("Subject: %s\n", subject);
968                 }
969                 fp = fopen(filename, "r");
970                 if (fp != NULL) {
971                         fmout(screenwidth, fp, NULL, NULL,
972                               ((userflags & US_PAGINATOR) ? 1 : 0),
973                               screenheight, 0, 0);
974                         beg = ftell(fp);
975                         fclose(fp);
976                 }
977                 goto MECR;
978         }
979         if (b == 'r') {
980                 replace_string(filename, 0L);
981                 goto MECR;
982         }
983         if (b == 'h') {
984                 return (2);
985         }
986         if (b == 'u') {
987                 if (subject != NULL) {
988                         newprompt("Subject: ", subject, 70);
989                 }
990                 goto MECR;
991         }
992
993 MEFIN:  return (0);
994
995 MEABT:  scr_printf("Are you sure? ");
996         if (yesno() == 0) {
997                 goto ME1;
998         }
999 MEABT2: unlink(filename);
1000         return (2);
1001 }
1002
1003
1004 #if 0
1005 /*
1006  * Transmit message text to the server.
1007  * 
1008  * This loop also implements a "tick" counter that displays the progress, if
1009  * we're sending something that will take a long time to transmit.
1010  */
1011 void transmit_message(CtdlIPC *ipc, FILE *fp)
1012 {
1013         char buf[SIZ];
1014         int ch, a;
1015         long msglen;
1016         time_t lasttick;
1017
1018         fseek(fp, 0L, SEEK_END);
1019         msglen = ftell(fp);
1020         rewind(fp);
1021         lasttick = time(NULL);
1022         strcpy(buf, "");
1023         while (ch = getc(fp), (ch >= 0)) {
1024                 if (ch == 10) {
1025                         if (!strcmp(buf, "000"))
1026                                 strcpy(buf, ">000");
1027                         CtdlIPC_putline(ipc, buf);
1028                         strcpy(buf, "");
1029                 } else {
1030                         a = strlen(buf);
1031                         buf[a + 1] = 0;
1032                         buf[a] = ch;
1033                         if ((ch == 32) && (strlen(buf) > 200)) {
1034                                 buf[a] = 0;
1035                                 if (!strcmp(buf, "000"))
1036                                         strcpy(buf, ">000");
1037                                 CtdlIPC_putline(ipc, buf);
1038                                 strcpy(buf, "");
1039                         }
1040                         if (strlen(buf) > 250) {
1041                                 if (!strcmp(buf, "000"))
1042                                         strcpy(buf, ">000");
1043                                 CtdlIPC_putline(ipc, buf);
1044                                 strcpy(buf, "");
1045                         }
1046                 }
1047
1048                 if ((time(NULL) - lasttick) > 2L) {
1049                         scr_printf(" %3ld%% completed\r",
1050                                ((ftell(fp) * 100L) / msglen));
1051                         scr_flush();
1052                         lasttick = time(NULL);
1053                 }
1054
1055         }
1056         CtdlIPC_putline(ipc, buf);
1057         scr_printf("                \r");
1058         scr_flush();
1059 }
1060 #endif
1061
1062
1063 /*
1064  * Make sure there's room in msg_arr[] for at least one more.
1065  */
1066 void check_msg_arr_size(void) {
1067         if ((num_msgs + 1) > msg_arr_size) {
1068                 msg_arr_size += 512;
1069                 msg_arr = realloc(msg_arr,
1070                         ((sizeof(long)) * msg_arr_size) );
1071         }
1072 }
1073
1074
1075
1076 /*
1077  * entmsg()  -  edit and create a message
1078  *              returns 0 if message was saved
1079  */
1080 int entmsg(CtdlIPC *ipc,
1081                 int is_reply,   /* nonzero if this was a <R>eply command */
1082                 int c)          /* mode */
1083 {
1084         char buf[SIZ];
1085         int a, b;
1086         int need_recp = 0;
1087         int mode;
1088         long highmsg = 0L;
1089         FILE *fp;
1090         char subject[SIZ];
1091         struct ctdlipcmessage message;
1092         unsigned long *msgarr = NULL;
1093         int r;                  /* IPC response code */
1094
1095         if (c > 0)
1096                 mode = 1;
1097         else
1098                 mode = 0;
1099
1100         strcpy(subject, "");
1101
1102         /*
1103          * First, check to see if we have permission to enter a message in
1104          * this room.  The server will return an error code if we can't.
1105          */
1106         strcpy(message.recipient, "");
1107         strcpy(message.author, "");
1108         strcpy(message.subject, "");
1109         message.text = message.author;  /* point to "", changes later */
1110         message.anonymous = 0;
1111         message.type = mode;
1112         r = CtdlIPCPostMessage(ipc, 0, &message, buf);
1113
1114         if (r / 100 != 2 && r / 10 != 57) {
1115                 scr_printf("%s\n", buf);
1116                 return (1);
1117         }
1118
1119         /* Error code 570 is special.  It means that we CAN enter a message
1120          * in this room, but a recipient needs to be specified.
1121          */
1122         need_recp = 0;
1123         if (r / 10 == 57)
1124                 need_recp = 1;
1125
1126         /* If the user is a dumbass, tell them how to type. */
1127         if ((userflags & US_EXPERT) == 0) {
1128                 formout(ipc, "entermsg");
1129         }
1130
1131         /* Handle the selection of a recipient, if necessary. */
1132         strcpy(buf, "");
1133         if (need_recp == 1) {
1134                 if (axlevel >= 2) {
1135                         if (is_reply) {
1136                                 strcpy(buf, reply_to);
1137                         } else {
1138                                 scr_printf("Enter recipient: ");
1139                                 getline(buf, (SIZ-100) );
1140                                 if (strlen(buf) == 0)
1141                                         return (1);
1142                         }
1143                 } else
1144                         strcpy(buf, "sysop");
1145         }
1146         strcpy(message.recipient, buf);
1147
1148         if (is_reply) {
1149                 if (strlen(reply_subject) > 0) {
1150                         if (!strncasecmp(reply_subject,
1151                            "Re: ", 3)) {
1152                                 strcpy(message.subject, reply_subject);
1153                         }
1154                         else {
1155                                 snprintf(message.subject,
1156                                         sizeof message.subject,
1157                                         "Re: %s",
1158                                         reply_subject);
1159                         }
1160                 }
1161         }
1162
1163         if (room_flags & QR_ANONOPT) {
1164                 scr_printf("Anonymous (Y/N)? ");
1165                 if (yesno() == 1)
1166                         message.anonymous = 1;
1167         }
1168
1169         /* If it's mail, we've got to check the validity of the recipient... */
1170         if (strlen(message.recipient) > 0) {
1171                 r = CtdlIPCPostMessage(ipc, 0, &message, buf);
1172                 if (r / 100 != 2) {
1173                         scr_printf("%s\n", buf);
1174                         return (1);
1175                 }
1176         }
1177
1178         /* Learn the number of the newest message in in the room, so we can
1179          * tell upon saving whether someone else has posted too.
1180          */
1181         num_msgs = 0;
1182         r = CtdlIPCGetMessages(ipc, LastMessages, 1, NULL, &msgarr, buf);
1183         if (r / 100 != 1) {
1184                 scr_printf("%s\n", buf);
1185         } else {
1186                 for (num_msgs = 0; msgarr[num_msgs]; num_msgs++)
1187                         ;
1188         }
1189
1190         /* Now compose the message... */
1191         if (client_make_message(ipc, temp, message.recipient, message.anonymous, 0, c, message.subject) != 0) {
1192                 return (2);
1193         }
1194
1195         /* Reopen the temp file that was created, so we can send it */
1196         fp = fopen(temp, "r");
1197
1198         /* Yes, unlink it now, so it doesn't stick around if we crash */
1199         unlink(temp);
1200
1201         if (!fp || !(message.text = load_message_from_file(fp))) {
1202                 err_printf("*** Internal error while trying to save message!\n"
1203                         "%s: %s\n",
1204                         temp, strerror(errno));
1205                 return(errno);
1206         }
1207
1208         if (fp) fclose(fp);
1209
1210         /* Transmit message to the server */
1211         r = CtdlIPCPostMessage(ipc, 1, &message, buf);
1212         if (r / 100 != 4) {
1213                 scr_printf("%s\n", buf);
1214                 return (1);
1215         }
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
1258         return(0);
1259 }
1260
1261 /*
1262  * Do editing on a quoted file
1263  */
1264 void process_quote(void)
1265 {
1266         FILE *qfile, *tfile;
1267         char buf[128];
1268         int line, qstart, qend;
1269
1270         /* Unlink the second temp file as soon as it's opened, so it'll get
1271          * deleted even if the program dies
1272          */
1273         qfile = fopen(temp2, "r");
1274         unlink(temp2);
1275
1276         /* Display the quotable text with line numbers added */
1277         line = 0;
1278         fgets(buf, 128, qfile);
1279         while (fgets(buf, 128, qfile) != NULL) {
1280                 scr_printf("%2d %s", ++line, buf);
1281         }
1282         scr_printf("Begin quoting at [ 1] : ");
1283         getline(buf, 3);
1284         qstart = (buf[0] == 0) ? (1) : atoi(buf);
1285         scr_printf("  End quoting at [%d] : ", line);
1286         getline(buf, 3);
1287         qend = (buf[0] == 0) ? (line) : atoi(buf);
1288         rewind(qfile);
1289         line = 0;
1290         fgets(buf, 128, qfile);
1291         tfile = fopen(temp, "w");
1292         while (fgets(buf, 128, qfile) != NULL) {
1293                 if ((++line >= qstart) && (line <= qend))
1294                         fprintf(tfile, " >%s", buf);
1295         }
1296         fprintf(tfile, " \n");
1297         fclose(qfile);
1298         fclose(tfile);
1299         chmod(temp, 0666);
1300 }
1301
1302
1303
1304 /*
1305  * List the URL's which were embedded in the previous message
1306  */
1307 void list_urls(CtdlIPC *ipc)
1308 {
1309         int i;
1310         char cmd[SIZ];
1311
1312         if (num_urls == 0) {
1313                 scr_printf("There were no URL's in the previous message.\n\n");
1314                 return;
1315         }
1316
1317         for (i = 0; i < num_urls; ++i) {
1318                 scr_printf("%3d %s\n", i + 1, urls[i]);
1319         }
1320
1321         if ((i = num_urls) != 1)
1322                 i = intprompt("Display which one", 1, 1, num_urls);
1323
1324         snprintf(cmd, sizeof cmd, rc_url_cmd, urls[i - 1]);
1325         system(cmd);
1326         scr_printf("\n");
1327 }
1328
1329
1330 /*
1331  * Run image viewer in background
1332  */
1333 int do_image_view(const char *filename)
1334 {
1335         char cmd[SIZ];
1336         pid_t childpid;
1337
1338         snprintf(cmd, sizeof cmd, imagecmd, filename);
1339         childpid = fork();
1340         if (childpid < 0) {
1341                 unlink(filename);
1342                 return childpid;
1343         }
1344
1345         if (childpid == 0) {
1346                 int retcode;
1347                 pid_t grandchildpid;
1348
1349                 grandchildpid = fork();
1350                 if (grandchildpid < 0) {
1351                         return grandchildpid;
1352                 }
1353
1354                 if (grandchildpid == 0) {
1355                         int nullfd;
1356                         int outfd = -1;
1357                         int errfd = -1;
1358
1359                         nullfd = open("/dev/null", O_WRONLY);
1360                         if (nullfd > -1) {
1361                                 dup2(1, outfd);
1362                                 dup2(2, errfd);
1363                                 dup2(nullfd, 1);
1364                                 dup2(nullfd, 2);
1365                         }
1366                         retcode = system(cmd);
1367                         if (nullfd > -1) {
1368                                 dup2(outfd, 1);
1369                                 dup2(errfd, 2);
1370                                 close(nullfd);
1371                         }
1372                         unlink(filename);
1373                         exit(retcode);
1374                 }
1375
1376                 if (grandchildpid > 0) {
1377                         exit(0);
1378                 }
1379         }
1380
1381         if (childpid > 0) {
1382                 int retcode;
1383
1384                 waitpid(childpid, &retcode, 0);
1385                 return retcode;
1386         }
1387         
1388         return -1;
1389 }
1390
1391
1392 /*
1393  * View an image attached to a message
1394  */
1395 void image_view(CtdlIPC *ipc, unsigned long msg)
1396 {
1397         struct parts *ptr = last_message_parts;
1398         char part[SIZ];
1399         int found = 0;
1400
1401         /* Run through available parts */
1402         for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1403                 if ((!strcasecmp(ptr->disposition, "attachment")
1404                    || !strcasecmp(ptr->disposition, "inline"))
1405                    && !strncmp(ptr->mimetype, "image/", 6)) {
1406                         found++;
1407                         if (found == 1) {
1408                                 strcpy(part, ptr->number);
1409                         }
1410                 }
1411         }
1412
1413         while (found > 0) {
1414                 if (found > 1)
1415                         strprompt("View which part (0 when done)", part, SIZ-1);
1416                 found = -found;
1417                 for (ptr = last_message_parts; ptr; ptr = ptr->next) {
1418                         if ((!strcasecmp(ptr->disposition, "attachment")
1419                            || !strcasecmp(ptr->disposition, "inline"))
1420                            && !strncmp(ptr->mimetype, "image/", 6)
1421                            && !strcasecmp(ptr->number, part)) {
1422                                 char tmp[PATH_MAX];
1423                                 char buf[SIZ];
1424                                 void *file = NULL; /* The downloaded file */
1425                                 int r;
1426         
1427                                 // view image
1428                                 found = -found;
1429                                 r = CtdlIPCAttachmentDownload(ipc, msg, ptr->number, &file, progress, buf);
1430                                 if (r / 100 != 2) {
1431                                         scr_printf("%s\n", buf);
1432                                 } else {
1433                                         size_t len;
1434         
1435                                         len = (size_t)extract_long(buf, 0);
1436                                         progress(len, len);
1437                                         scr_flush();
1438                                         snprintf(tmp, sizeof tmp, "%s.%s",
1439                                                 tmpnam(NULL),
1440                                                 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         strcpy(prtfile, tmpnam(NULL));
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                                 sttybbs(SB_RESTORE);
1563                                 ka_system(printcmd);
1564                                 sttybbs(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 == 3)
1581                         return;
1582                 if (((userflags & US_NOPROMPT) || (e == 2))
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 && strlen(imagecmd) > 0)
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) ==
1612                                             0)) {
1613                                         if ((e == 'd') || (e == 'm'))
1614                                                 e = 0;
1615                                 }
1616 /* print only if available */
1617                                 if ((e == 'p') && (strlen(printcmd) == 0))
1618                                         e = 0;
1619 /* can't file if not allowed */
1620                                     if ((e == 'f')
1621                                         && (rc_allow_attachments == 0))
1622                                         e = 0;
1623 /* link only if browser avail*/
1624                                     if ((e == 'u')
1625                                         && (strlen(rc_url_cmd) == 0))
1626                                         e = 0;
1627                                 if ((e == 'i')
1628                                         && (!strlen(imagecmd) || !has_images))
1629                                         e = 0;
1630                         } while ((e != 'a') && (e != 'n') && (e != 's')
1631                                  && (e != 'd') && (e != 'm') && (e != 'p')
1632                                  && (e != 'q') && (e != 'b') && (e != 'h')
1633                                  && (e != 'r') && (e != 'f') && (e != '?')
1634                                  && (e != 'u') && (e != 'c') && (e != 'y')
1635                                  && (e != 'i'));
1636                         switch (e) {
1637                         case 's':
1638                                 scr_printf("Stop");
1639                                 break;
1640                         case 'a':
1641                                 scr_printf("Again");
1642                                 break;
1643                         case 'd':
1644                                 scr_printf("Delete");
1645                                 break;
1646                         case 'm':
1647                                 scr_printf("Move");
1648                                 break;
1649                         case 'c':
1650                                 scr_printf("Copy");
1651                                 break;
1652                         case 'n':
1653                                 scr_printf("Next");
1654                                 break;
1655                         case 'p':
1656                                 scr_printf("Print");
1657                                 break;
1658                         case 'q':
1659                                 scr_printf("Quote");
1660                                 break;
1661                         case 'b':
1662                                 scr_printf("Back");
1663                                 break;
1664                         case 'h':
1665                                 scr_printf("Header");
1666                                 break;
1667                         case 'r':
1668                                 scr_printf("Reply");
1669                                 break;
1670                         case 'f':
1671                                 scr_printf("File");
1672                                 break;
1673                         case 'u':
1674                                 scr_printf("URL's");
1675                                 break;
1676                         case 'y':
1677                                 scr_printf("mY next");
1678                                 break;
1679                         case 'i':
1680                                 break;
1681                         case '?':
1682                                 scr_printf("? <help>");
1683                                 break;
1684                         }
1685                         if (userflags & US_DISAPPEAR || e == 'i')
1686                                 scr_printf("\r%79s\r", "");
1687                         else
1688                                 scr_printf("\n");
1689                         scr_flush();
1690                 }
1691                 switch (e) {
1692                 case '?':
1693                         scr_printf("Options available here:\n"
1694                                 " ?  Help (prints this message)\n"
1695                                 " S  Stop reading immediately\n"
1696                                 " A  Again (repeats last message)\n"
1697                                 " N  Next (continue with next message)\n"
1698                                 " Y  My Next (continue with next message you authored)\n"
1699                                 " B  Back (go back to previous message)\n");
1700                         if ((is_room_aide)
1701                             || (room_flags & QR_MAILBOX)) {
1702                                 scr_printf(" D  Delete this message\n"
1703                                         " M  Move message to another room\n");
1704                         }
1705                         scr_printf(" C  Copy message to another room\n");
1706                         if (strlen(printcmd) > 0)
1707                                 scr_printf(" P  Print this message\n");
1708                         scr_printf(
1709                                 " Q  Quote portions of this message for your next post\n"
1710                                 " H  Headers (display message headers only)\n");
1711                         if (is_mail)
1712                                 scr_printf(" R  Reply to this message\n");
1713                         if (rc_allow_attachments)
1714                                 scr_printf
1715                                     (" F  (save attachments to a file)\n");
1716                         if (strlen(rc_url_cmd) > 0)
1717                                 scr_printf(" U  (list URL's for display)\n");
1718                         if (strlen(imagecmd) > 0 && has_images > 0)
1719                                 scr_printf(" I  Image viewer\n");
1720                         scr_printf("\n");
1721                         goto RMSGREAD;
1722                 case 'p':
1723                         scr_flush();
1724                         dest = fopen(prtfile, "w");
1725                         arcflag = 1;
1726                         hold_color = enable_color;
1727                         enable_color = 0;
1728                         goto RAGAIN;
1729                 case 'q':
1730                         scr_flush();
1731                         dest = fopen(temp2, "w");
1732                         quotflag = 1;
1733                         hold_color = enable_color;
1734                         enable_color = 0;
1735                         goto RAGAIN;
1736                 case 's':
1737                         return;
1738                 case 'a':
1739                         goto RAGAIN;
1740                 case 'b':
1741                         a = a - (rdir * 2);
1742                         break;
1743                 case 'm':
1744                 case 'c':
1745                         newprompt("Enter target room: ",
1746                                   targ, ROOMNAMELEN - 1);
1747                         if (strlen(targ) > 0) {
1748                                 r = CtdlIPCMoveMessage(ipc, (e == 'c' ? 1 : 0),
1749                                                        msg_arr[a], targ, cmd);
1750                                 scr_printf("%s\n", cmd);
1751                                 if (r / 100 == 2)
1752                                         msg_arr[a] = 0L;
1753                         } else {
1754                                 goto RMSGREAD;
1755                         }
1756                         if (r / 100 != 2)       /* r will be init'ed, FIXME */
1757                                 goto RMSGREAD;  /* the logic here sucks */
1758                         break;
1759                 case 'f':
1760                         newprompt("Which section? ", filename,
1761                                   ((sizeof filename) - 1));
1762                         r = CtdlIPCAttachmentDownload(ipc, msg_arr[a],
1763                                         filename, &attachment, progress, cmd);
1764                         if (r / 100 != 2) {
1765                                 scr_printf("%s\n", cmd);
1766                         } else {
1767                                 extract(filename, cmd, 2);
1768                                 /*
1769                                  * Part 1 won't have a filename; use the
1770                                  * subject of the message instead. IO
1771                                  */
1772                                 if (!strlen(filename))
1773                                         strcpy(filename, reply_subject);
1774                                 destination_directory(save_to, filename);
1775                                 save_buffer(attachment,
1776                                                 extract_unsigned_long(cmd, 0),
1777                                                 save_to);
1778                         }
1779                         if (attachment) {
1780                                 free(attachment);
1781                                 attachment = NULL;
1782                         }
1783                         goto RMSGREAD;
1784                 case 'd':
1785                         scr_printf("*** Delete this message? ");
1786                         if (yesno() == 1) {
1787                                 r = CtdlIPCDeleteMessage(ipc, msg_arr[a], cmd);
1788                                 scr_printf("%s\n", cmd);
1789                                 if (r / 100 == 2)
1790                                         msg_arr[a] = 0L;
1791                         } else {
1792                                 goto RMSGREAD;
1793                         }
1794                         break;
1795                 case 'h':
1796                         read_message(ipc, msg_arr[a], READ_HEADER, NULL);
1797                         goto RMSGREAD;
1798                 case 'r':
1799                         savedpos = num_msgs;
1800                         entmsg(ipc, 1, (rc_reply_extedit ? 2 : 0));
1801                         num_msgs = savedpos;
1802                         goto RMSGREAD;
1803                 case 'u':
1804                         list_urls(ipc);
1805                         goto RMSGREAD;
1806                 case 'i':
1807                         image_view(ipc, msg_arr[a]);
1808                         goto RMSGREAD;
1809             case 'y':
1810           { /* hack hack hack */
1811             /* find the next message by me, stay here if we find nothing */
1812             int finda;
1813             int lasta = a;
1814             for (finda = a; ((finda < num_msgs) && (finda >= 0)); finda += rdir)
1815               {
1816                 /* This is repetitively dumb, but that's what computers are for.
1817                    We have to load up messages until we find one by us */
1818                 char buf[SIZ];
1819                 int founda = 0;
1820                 
1821                 /* read the header so we can get 'from=' */
1822                 snprintf(buf, sizeof buf, "MSG0 %ld|1", msg_arr[finda]);
1823                 CtdlIPC_putline(ipc, buf);
1824                 CtdlIPC_getline(ipc, buf);
1825                 while (CtdlIPC_getline(ipc, buf), strcmp(buf, "000")) 
1826                   {
1827                         if ((!strncasecmp(buf, "from=", 5)) && (finda != a)) /* Skip current message. */
1828                       { 
1829                         if (strcasecmp(buf+5, fullname) == 0)
1830                           {
1831                             a = lasta; /* meesa current */
1832                             founda = 1;
1833                           }
1834                           }
1835                   }
1836                     /* we are now in synch with the server */
1837                 if (founda)
1838                   break; /* for */
1839                 lasta = finda; /* keep one behind or we skip on the reentrance to the for */
1840               } /* for */
1841           } /* case 'y' */
1842       } /* switch */
1843         }                       /* end for loop */
1844 }                               /* end read routine */
1845
1846
1847
1848
1849 /*
1850  * View and edit a system message
1851  */
1852 void edit_system_message(CtdlIPC *ipc, char *which_message)
1853 {
1854         char desc[SIZ];
1855         char read_cmd[SIZ];
1856         char write_cmd[SIZ];
1857
1858         snprintf(desc, sizeof desc, "system message '%s'", which_message);
1859         snprintf(read_cmd, sizeof read_cmd, "MESG %s", which_message);
1860         snprintf(write_cmd, sizeof write_cmd, "EMSG %s", which_message);
1861         do_edit(ipc, desc, read_cmd, "NOOP", write_cmd);
1862 }
1863
1864
1865
1866
1867 /*
1868  * Verify the message base
1869  */
1870 void check_message_base(CtdlIPC *ipc)
1871 {
1872         char buf[SIZ];
1873         char *transcript = NULL;
1874         int r;          /* IPC response code */
1875
1876         scr_printf
1877             ("Please read the documentation before running this command.\n"
1878             "Having done so, do you still want to check the message base? ");
1879         if (yesno() == 0)
1880                 return;
1881
1882         r = CtdlIPCMessageBaseCheck(ipc, &transcript, buf);
1883         if (r / 100 != 1) {
1884                 scr_printf("%s\n", buf);
1885                 return;
1886         }
1887
1888         while (transcript && strlen(transcript)) {
1889                 lines_printed = 1;
1890                 extract_token(buf, transcript, 0, '\n');
1891                 remove_token(transcript, 0, '\n');
1892                 pprintf("%s\n", buf);
1893         }
1894         if (transcript) free(transcript);
1895         return;
1896 }
1897
1898
1899 /*
1900  * Loads the contents of a file into memory.  Caller must free the allocated
1901  * memory.
1902  */
1903 char *load_message_from_file(FILE *src)
1904 {
1905         size_t i;
1906         size_t got = 0;
1907         char *dest = NULL;
1908
1909         fseek(src, 0, SEEK_END);
1910         i = ftell(src);
1911         rewind(src);
1912
1913         dest = (char *)calloc(1, i + 1);
1914         if (!dest)
1915                 return NULL;
1916
1917         while (got < i) {
1918                 size_t g;
1919
1920                 g = fread(dest + got, 1, i - got, src);
1921                 got += g;
1922                 if (g < i - got) {
1923                         /* Interrupted system call, keep going */
1924                         if (errno == EINTR)
1925                                 continue;
1926                         /* At this point we have either EOF or error */
1927                         i = got;
1928                         break;
1929                 }
1930                 dest[i] = 0;
1931         }
1932
1933         return dest;
1934 }