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