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