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