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