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