forw/repl/dist annotations won't add address lists anymore.
[mmh] / uip / sendsbr.c
1 /*
2 ** sendsbr.c -- routines to help WhatNow/Send along
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/signals.h>
11 #include <setjmp.h>
12 #include <signal.h>
13 #include <fcntl.h>
14 #include <h/mime.h>
15 #include <h/tws.h>
16 #include <h/utils.h>
17
18 #ifdef TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # ifdef TM_IN_SYS_TIME
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 int debugsw = 0;  /* global */
30 int forwsw  = 1;
31 int inplace = 1;
32 int pushsw  = 0;
33 int verbsw  = 0;
34
35 char *altmsg   = NULL;  /*  .. */
36 char *annotext = NULL;
37 char *distfile = NULL;
38
39 static jmp_buf env;
40
41 /* name of temp file for body content */
42 static char body_file_name[MAXPATHLEN + 1];
43 /* name of mhbuild composition temporary file */
44 static char composition_file_name[MAXPATHLEN + 1]; 
45 static int field_size;  /* size of header field buffer */
46 static char *field;  /* header field buffer */
47 static FILE *draft_file;  /* draft file pointer */
48 static FILE *body_file;  /* body file pointer */
49 static FILE *composition_file;  /* composition file pointer */
50
51 /*
52 ** external prototypes
53 */
54 int sendsbr(char **, int, char *, struct stat *, int);
55 char *getusername(void);
56
57 /*
58 ** static prototypes
59 */
60 static void armed_done(int) NORETURN;
61 static void alert(char *, int);
62 static int tmp_fd(void);
63 static void anno(int, struct stat *);
64 static void annoaux(int);
65 static int sendaux(char **, int, char *, struct stat *);
66
67 static int attach(char *);
68 static void clean_up_temporary_files(void);
69 static int get_line(void);
70 static void make_mime_composition_file_entry(char *);
71
72
73 /*
74 ** Entry point into (back-end) routines to send message.
75 */
76
77 int
78 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
79 {
80         int status;
81         char buffer[BUFSIZ];
82         char *original_draft;  /* name of original draft file */
83         char *p;  /* string pointer for building file name */
84
85         /*
86         ** Save the original name of the draft file.  The name of the
87         ** draft file is changed to a temporary file containing the built
88         ** MIME message if there are attachments.  We need the original
89         ** name so that it can be renamed after the message is sent.
90         */
91
92         original_draft = drft;
93
94         /*
95         ** Convert the draft to a MIME message.
96         ** Use the mhbuild composition file for the draft if there was
97         ** a successful conversion because that now contains the MIME
98         ** message.  A nice side effect of this is that it leaves the
99         ** original draft file untouched so that it can be retrieved
100         ** and modified if desired.
101         */
102         switch (attach(drft)) {
103         case OK:
104                 drft = composition_file_name;
105                 break;
106
107         case NOTOK:
108                 return (NOTOK);
109
110         case DONE:
111                 break;
112         }
113
114         done=armed_done;
115         switch (setjmp(env)) {
116         case OK:
117                 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
118                 /* rename the original draft */
119                 if (rename_drft && status == OK &&
120                                 rename(original_draft, strncpy(buffer,
121                                 m_backup(original_draft), sizeof(buffer)))
122                                 == NOTOK)
123                         advise(buffer, "unable to rename %s to", drft);
124                 break;
125
126         default:
127                 status = DONE;
128                 break;
129         }
130
131         done=exit;
132         if (distfile)
133                 unlink(distfile);
134
135         /*
136         ** Get rid of any temporary files that we created for attachments.
137         ** Also get rid of the renamed composition file that mhbuild
138         ** leaves as a turd.  It looks confusing, but we use the body
139         ** file name to help build the renamed composition file name.
140         */
141
142         if (drft == composition_file_name) {
143                 clean_up_temporary_files();
144
145                 if (strlen(composition_file_name) >=
146                                 sizeof (composition_file_name) - 6)
147                         advise(NULL, "unable to remove original composition file.");
148
149                 else {
150                         if ((p = strrchr(composition_file_name, '/')) == NULL)
151                                 p = composition_file_name;
152                         else
153                                 p++;
154
155                         strcpy(body_file_name, p);
156                         *p++ = ',';
157                         strcpy(p, body_file_name);
158                         strcat(p, ".orig");
159
160                         unlink(composition_file_name);
161                 }
162         }
163
164         return status;
165 }
166
167 static int
168 attach(char *draft_file_name)
169 {
170         char buf[MAXPATHLEN + 6];  /* miscellaneous buffer */
171         int c;  /* current character for body copy */
172         int has_attachment;  /* draft has at least one attachment */
173         int has_body;  /* draft has a message body */
174         int non_ascii; /* msg body contains non-ASCII chars */
175         int length;  /* length of attachment header field name */
176         char *p;  /* miscellaneous string pointer */
177
178         /* Open up the draft file. */
179         if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
180                 adios(NULL, "can't open draft file `%s'.",
181                                 draft_file_name);
182
183         /*
184         **  Allocate a buffer to hold the header components as they're read in.
185         **  This buffer might need to be quite large, so we grow it as needed.
186         */
187         field = (char *)mh_xmalloc(field_size = 256);
188
189         /*
190         ** Scan the draft file for an attachment header field name.
191         ** The existence of one indicates that the
192         ** draft has attachments.  Bail out if there are no attachments
193         ** because we're done.  Read to the end of the headers even if
194         ** we have no attachments.
195         */
196         length = strlen(attach_hdr);
197
198         has_attachment = 0;
199
200         while (get_line() != EOF && *field != '\0' && *field != '-')
201                 if (strncasecmp(field, attach_hdr, length) == 0 &&
202                                 field[length] == ':')
203                         has_attachment = 1;
204
205         /*
206         ** We have at least one attachment.  Look for at least one
207         ** non-blank line in the body of the message which indicates
208         ** content in the body.
209         ** Check if body contains at least one non-blank (= not empty)
210         ** and if it contains any non-ASCII chars (= need MIME).
211         */
212         has_body = 0;
213         non_ascii = 0;
214
215         while (get_line() != EOF) {
216                 for (p = field; *p != '\0'; p++) {
217                         if (*p != ' ' && *p != '\t') {
218                                 has_body = 1;
219                         }
220                         if (*p > 127 || *p < 0) {
221                                 non_ascii = 1;
222                         }
223                 }
224                 if (has_body && non_ascii)
225                         break;
226         }
227
228         /*
229         ** Bail out if there are no attachments and only ASCII text.
230         ** This means we don't need to convert it to MIME.
231         */
232         if (!has_attachment && non_ascii==0) {
233                 return DONE;
234         }
235
236         /*
237         ** Else: mimify
238         */
239
240         /* Make names for the temporary files.  */
241         strncpy(body_file_name,
242                         m_mktemp(toabsdir(invo_name), NULL, NULL),
243                         sizeof (body_file_name));
244         strncpy(composition_file_name,
245                         m_mktemp(toabsdir(invo_name), NULL, NULL),
246                         sizeof (composition_file_name));
247
248         if (has_body)
249                 body_file = fopen(body_file_name, "w");
250
251         composition_file = fopen(composition_file_name, "w");
252
253         if ((has_body && body_file == (FILE *)0) ||
254                         composition_file == (FILE *)0) {
255                 clean_up_temporary_files();
256                 adios(NULL, "unable to open all of the temporary files.");
257         }
258
259         /*
260         ** Start at the beginning of the draft file.  Copy all
261         ** non-attachment header fields to the temporary composition file.
262         ** Then add the dashed line separator.
263         */
264         rewind(draft_file);
265         while (get_line() != EOF && *field != '\0' && *field != '-')
266                 if (strncasecmp(field, attach_hdr, length) != 0 ||
267                                 field[length] != ':')
268                         fprintf(composition_file, "%s\n", field);
269         fputs("--------\n", composition_file);
270
271         /*
272         ** Copy the message body to a temporary file.
273         */
274         if (has_body) {
275                 while ((c = getc(draft_file)) != EOF)
276                                 putc(c, body_file);
277                 fclose(body_file);
278         }
279
280         /*
281         ** Add a mhbuild MIME composition file line for the body if
282         ** there was one.
283         */
284         if (has_body) {
285                 /* old: make_mime_composition_file_entry(body_file_name); */
286                 /* charset will be discovered/guessed by buildmimeproc */
287                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
288         }
289
290         /*
291         ** Now, go back to the beginning of the draft file and look for
292         ** header fields that specify attachments.  Add a mhbuild MIME
293         ** composition file for each.
294         */
295         rewind(draft_file);
296         while (get_line() != EOF && *field != '\0' && *field != '-') {
297                 if (strncasecmp(field, attach_hdr, length) == 0 &&
298                                 field[length] == ':') {
299                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
300                                 continue;
301                         }
302                         if (*p == '+') {
303                                 /* forwarded message */
304                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
305                         } else {
306                                 make_mime_composition_file_entry(p);
307                         }
308                 }
309         }
310
311         fclose(composition_file);
312
313         /*
314         ** We're ready to roll!  Run mhbuild on the composition file.
315         ** Note that mhbuild is in the context as buildmimeproc.
316         */
317         sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
318
319         if (system(buf) != 0) {
320                 clean_up_temporary_files();
321                 return (NOTOK);
322         }
323
324         return (OK);
325 }
326
327 static void
328 clean_up_temporary_files(void)
329 {
330         unlink(body_file_name);
331         unlink(composition_file_name);
332
333         return;
334 }
335
336 static int
337 get_line(void)
338 {
339         int c;  /* current character */
340         int n;  /* number of bytes in buffer */
341         char *p;  /* buffer pointer */
342
343         /*
344         ** Get a line from the input file, growing the field buffer as
345         ** needed.  We do this so that we can fit an entire line in the
346         ** buffer making it easy to do a string comparison on both the
347         ** field name and the field body which might be a long path name.
348         */
349
350         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
351                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
352                         ungetc(c, draft_file);
353                         c = '\n';
354                         break;
355                 }
356
357                 if (++n >= field_size - 1) {
358                         field = (char *)mh_xrealloc((void *)field, field_size += 256);
359
360                         p = field + n - 1;
361                 }
362         }
363
364         /* NUL-terminate the field. */
365         *p = '\0';
366
367         return (c);
368 }
369
370 static void
371 make_mime_composition_file_entry(char *file_name)
372 {
373         int binary;  /* binary character found flag */
374         int c;  /* current character */
375         char *content_type;  /* mime content type */
376         FILE *fp;  /* content and pipe file pointer */
377         struct node *np;  /* context scan node pointer */
378         char *p;  /* miscellaneous string pointer */
379
380         content_type = NULL;
381
382         /*
383         ** Check the file name for a suffix.  Scan the context for that
384         ** suffix on a mhshow-suffix- entry.  We use these entries to
385         ** be compatible with mhshow, and there's no reason to make the
386         ** user specify each suffix twice.  Context entries of the form
387         ** "mhshow-suffix-contenttype" in the name have the suffix in
388         ** the field, including the dot.
389         */
390
391         if ((p = strrchr(file_name, '.')) != NULL) {
392                 for (np = m_defs; np; np = np->n_next) {
393                         if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0
394                                         && mh_strcasecmp(p, np->n_field) == 0)
395                                         {
396                                 content_type = np->n_name + 14;
397                                 break;
398                         }
399                 }
400         }
401
402         /*
403         ** No content type was found, either because there was no matching
404         ** entry in the context or because the file name has no suffix.
405         ** Open the file and check for non-ASCII characters.  Choose the
406         ** content type based on this check.
407         */
408
409         if (content_type == NULL) {
410                 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
411                         clean_up_temporary_files();
412                         adios(NULL, "unable to access file \"%s\"",
413                                         file_name);
414                 }
415
416                 binary = 0;
417
418                 while ((c = getc(fp)) != EOF) {
419                         if (c > 127 || c < 0) {
420                                 binary = 1;
421                                 break;
422                         }
423                 }
424
425                 fclose(fp);
426
427                 content_type = binary ?
428                                 "application/octet-stream" : "text/plain";
429         }
430
431         /*
432         ** Make sure that the attachment file exists and is readable.
433         ** Append a mhbuild directive to the draft file.  This starts with
434         ** the content type.  Append a file name attribute and a private
435         ** x-unix-mode attribute.  Also append a description obtained
436         ** (if possible) by running the "file" command on the file.
437         */
438
439         if (access(file_name, R_OK) != 0) {
440                 clean_up_temporary_files();
441                 adios(NULL, "unable to access file \"%s\"", file_name);
442         }
443
444
445         if (stringdex(toabsdir(invo_name), file_name) == 0) {
446                 /*
447                 ** Content had been placed by send into a temp file.
448                 ** Don't generate Content-Disposition header, because
449                 ** it confuses Microsoft Outlook, Build 10.0.6626, at
450                 ** least.
451                 */
452                 fprintf(composition_file, "#%s <>", content_type);
453         } else {
454                 /*
455                 ** Suppress Content-Id, insert simple
456                 ** Content-Disposition.
457                 */
458                 fprintf(composition_file,
459                         "#%s; name=\"%s\" <>{attachment}",
460                         content_type,
461                         ((p = strrchr(file_name, '/')) == NULL) ?
462                         file_name : p + 1);
463         }
464
465         /* Finish up with the file name. */
466         fprintf(composition_file, " %s\n", file_name);
467
468         return;
469 }
470
471 /*
472 ** Annotate original message, and
473 ** call `postproc' to send message.
474 */
475
476 static int
477 sendaux(char **vec, int vecp, char *drft, struct stat *st)
478 {
479         pid_t child_id;
480         int i, status, fd, fd2;
481         char backup[BUFSIZ];
482
483         fd = pushsw ? tmp_fd() : NOTOK;
484         fd2 = NOTOK;
485
486         vec[vecp++] = drft;
487         if (annotext && (fd2 = tmp_fd()) == NOTOK) {
488                 admonish(NULL, "unable to create file for annotation list");
489         }
490         if (distfile && distout(drft, distfile, backup) == NOTOK)
491                 done(1);
492         vec[vecp] = NULL;
493
494         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
495                 sleep(5);
496
497         switch (child_id) {
498         case -1:
499                 /* oops -- fork error */
500                 adios("fork", "unable to");
501                 break;  /* NOT REACHED */
502
503         case 0:
504                 /*
505                 ** child process -- send it
506                 **
507                 ** If fd is ok, then we are pushing and fd points to temp
508                 ** file, so capture anything on stdout and stderr there.
509                 */
510                 if (fd != NOTOK) {
511                         dup2(fd, fileno(stdout));
512                         dup2(fd, fileno(stderr));
513                         close(fd);
514                 }
515                 execvp(postproc, vec);
516                 fprintf(stderr, "unable to exec ");
517                 perror(postproc);
518                 _exit(-1);
519                 break;  /* NOT REACHED */
520
521         default:
522                 /*
523                 ** parent process -- wait for it
524                 */
525                 if ((status = pidwait(child_id, NOTOK)) == OK) {
526                         if (annotext && fd2 != NOTOK)
527                                 anno(fd2, st);
528                 } else {
529                         /*
530                         ** If postproc failed, and we have good fd (which
531                         ** means we pushed), then mail error message
532                         ** (and possibly the draft) back to the user.
533                         */
534                         if (fd != NOTOK) {
535                                 alert(drft, fd);
536                                 close(fd);
537                         } else {
538                                 advise(NULL, "message not delivered to anyone");
539                         }
540                         if (annotext && fd2 != NOTOK)
541                                 close(fd2);
542                         if (distfile) {
543                                 unlink(drft);
544                                 if (rename(backup, drft) == NOTOK)
545                                         advise(drft, "unable to rename %s to",
546                                                         backup);
547                         }
548                 }
549                 break;
550         }
551
552         return status;
553 }
554
555
556 /*
557 ** Mail error notification (and possibly a copy of the
558 ** message) back to the user, using the mailproc
559 */
560
561 static void
562 alert(char *file, int out)
563 {
564         pid_t child_id;
565         int i, in;
566         char buf[BUFSIZ];
567
568         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
569                 sleep(5);
570
571         switch (child_id) {
572         case NOTOK:
573                 /* oops -- fork error */
574                 advise("fork", "unable to");
575
576         case OK:
577                 /* child process -- send it */
578                 SIGNAL(SIGHUP, SIG_IGN);
579                 SIGNAL(SIGINT, SIG_IGN);
580                 SIGNAL(SIGQUIT, SIG_IGN);
581                 SIGNAL(SIGTERM, SIG_IGN);
582                 if (forwsw) {
583                         if ((in = open(file, O_RDONLY)) == NOTOK) {
584                                 admonish(file, "unable to re-open");
585                         } else {
586                                 lseek(out, (off_t) 0, SEEK_END);
587                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
588                                 write(out, buf, strlen(buf));
589                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
590                                 write(out, buf, strlen(buf));
591                                 cpydgst(in, out, file, "temporary file");
592                                 close(in);
593                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
594                                 write(out, buf, strlen(buf));
595                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
596                                         admonish(buf, "unable to rename %s to", file);
597                         }
598                 }
599                 lseek(out, (off_t) 0, SEEK_SET);
600                 dup2(out, fileno(stdin));
601                 close(out);
602                 /* create subject for error notification */
603                 snprintf(buf, sizeof(buf), "send failed on %s",
604                                 forwsw ? "enclosed draft" : file);
605
606                 execlp(mailproc, mhbasename(mailproc), getusername(),
607                                 "-subject", buf, NULL);
608                 fprintf(stderr, "unable to exec ");
609                 perror(mailproc);
610                 _exit(-1);
611
612         default:  /* no waiting... */
613                 break;
614         }
615 }
616
617
618 static int
619 tmp_fd(void)
620 {
621         int fd;
622         char *tfile = NULL;
623
624         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
625         if (tfile == NULL) return NOTOK;
626         fchmod(fd, 0600);
627
628         if (debugsw)
629                 advise(NULL, "temporary file %s selected", tfile);
630         else
631                 if (unlink(tfile) == NOTOK)
632                         advise(tfile, "unable to remove");
633
634         return fd;
635 }
636
637
638 static void
639 anno(int fd, struct stat *st)
640 {
641         pid_t child_id;
642         sigset_t set, oset;
643         static char *cwd = NULL;
644         struct stat st2;
645
646         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
647                         st->st_mtime != st2.st_mtime ||
648                         st->st_dev != st2.st_dev ||
649                         st->st_ino != st2.st_ino)) {
650                 if (debugsw)
651                         admonish(NULL, "$mhaltmsg mismatch");
652                 return;
653         }
654
655         child_id = debugsw ? NOTOK : fork();
656         switch (child_id) {
657         case NOTOK:  /* oops */
658                 if (!debugsw)
659                         advise(NULL, "unable to fork, so doing annotations by hand...");
660                 if (cwd == NULL)
661                         cwd = getcpy(pwd());
662
663         case OK:
664                 /* block a few signals */
665                 sigemptyset(&set);
666                 sigaddset(&set, SIGHUP);
667                 sigaddset(&set, SIGINT);
668                 sigaddset(&set, SIGQUIT);
669                 sigaddset(&set, SIGTERM);
670                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
671
672                 annoaux(fd);
673                 if (child_id == OK)
674                         _exit(0);
675
676                 /* reset the signal mask */
677                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
678
679                 chdir(cwd);
680                 break;
681
682         default:  /* no waiting... */
683                 close(fd);
684                 break;
685         }
686 }
687
688
689 static void
690 annoaux(int fd)
691 {
692         int fd2, fd3, msgnum;
693         char *cp, *folder, *maildir;
694         char buffer[BUFSIZ], **ap;
695         FILE *fp;
696         struct msgs *mp;
697
698         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
699                 if (debugsw)
700                         admonish(NULL, "$mhfolder not set");
701                 return;
702         }
703         maildir = toabsdir(folder);
704         if (chdir(maildir) == NOTOK) {
705                 if (debugsw)
706                         admonish(maildir, "unable to change directory to");
707                 return;
708         }
709         if (!(mp = folder_read(folder))) {
710                 if (debugsw)
711                         admonish(NULL, "unable to read folder %s", folder);
712                 return;
713         }
714
715         /* check for empty folder */
716         if (mp->nummsg == 0) {
717                 if (debugsw)
718                         admonish(NULL, "no messages in %s", folder);
719                 goto oops;
720         }
721
722         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
723                 if (debugsw)
724                         admonish(NULL, "$mhmessages not set");
725                 goto oops;
726         }
727         if (!debugsw  /* MOBY HACK... */
728                         && pushsw
729                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
730                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
731                 dup2(fd3, fileno(stderr));
732                 close(fd3);
733         }
734         else
735                 fd2 = NOTOK;
736         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
737                 m_convert(mp, *ap);
738         free(cp);
739         if (fd2 != NOTOK)
740                 dup2(fd2, fileno(stderr));
741         if (mp->numsel == 0) {
742                 if (debugsw)
743                         admonish(NULL, "no messages to annotate");
744                 goto oops;
745         }
746
747         lseek(fd, (off_t) 0, SEEK_SET);
748         if ((fp = fdopen(fd, "r")) == NULL) {
749                 if (debugsw)
750                         admonish(NULL, "unable to fdopen annotation list");
751                 goto oops;
752         }
753         cp = NULL;
754         while (fgets(buffer, sizeof(buffer), fp) != NULL)
755                 cp = add(buffer, cp);
756         fclose(fp);
757
758         if (debugsw)
759                 advise(NULL, "annotate%s with %s: \"%s\"",
760                                 inplace ? " inplace" : "", annotext, cp);
761         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
762                 if (is_selected(mp, msgnum)) {
763                         if (debugsw)
764                                 advise(NULL, "annotate message %d", msgnum);
765                         annotate(m_name(msgnum), annotext, cp, inplace,
766                                         1, -2, 0);
767                 }
768         }
769
770         free(cp);
771
772 oops:
773         folder_free(mp);  /* free folder/message structure */
774 }
775
776
777 static void
778 armed_done(int status)
779 {
780         longjmp(env, status ? status : NOTOK);
781
782         exit(status);
783 }