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