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