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