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