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