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