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