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