89a07487cfa461e5d673786fc67999cbd004d475
[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
207         /*
208         ** Look for at least one non-blank line in the body of the
209         ** message which indicates content in the body.
210         ** Check if body contains at least one non-blank (= not empty)
211         ** and if it contains any non-ASCII chars (= need MIME).
212         */
213         has_body = 0;
214         non_ascii = 0;
215
216         while (get_line() != EOF) {
217                 for (p = field; *p != '\0'; p++) {
218                         if (*p != ' ' && *p != '\t') {
219                                 has_body = 1;
220                         }
221                         if (*p > 127 || *p < 0) {
222                                 non_ascii = 1;
223                         }
224                 }
225                 if (has_body && non_ascii)
226                         break;
227         }
228
229         /*
230         ** Bail out if there are no attachments and only ASCII text.
231         ** This means we don't need to convert it to MIME.
232         */
233         if (!has_attachment && non_ascii==0) {
234                 return DONE;
235         }
236
237         /*
238         ** Else: mimify
239         */
240
241         /* Make names for the temporary files.  */
242         strncpy(body_file_name,
243                         m_mktemp(toabsdir(invo_name), NULL, NULL),
244                         sizeof (body_file_name));
245         strncpy(composition_file_name,
246                         m_mktemp(toabsdir(invo_name), NULL, NULL),
247                         sizeof (composition_file_name));
248
249         if (has_body)
250                 body_file = fopen(body_file_name, "w");
251
252         composition_file = fopen(composition_file_name, "w");
253
254         if ((has_body && !body_file) || !composition_file) {
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 && *field != '-') {
266                 if (strncasecmp(field, attach_hdr, length) != 0 ||
267                                 field[length] != ':') {
268                         fprintf(composition_file, "%s\n", field);
269                 }
270         }
271         fputs("--------\n", composition_file);
272
273         if (has_body) {
274                 /* Copy the message body to the temporary file. */
275                 while ((c = getc(draft_file)) != EOF) {
276                         putc(c, body_file);
277                 }
278                 fclose(body_file);
279
280                 /* Add a mhbuild MIME composition file line for the body */
281                 /* charset will be discovered/guessed by buildmimeproc */
282                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
283         }
284
285         /*
286         ** Now, go back to the beginning of the draft file and look for
287         ** header fields that specify attachments.  Add a mhbuild MIME
288         ** composition file for each.
289         */
290         rewind(draft_file);
291         while (get_line() != EOF && *field && *field != '-') {
292                 if (strncasecmp(field, attach_hdr, length) == 0 &&
293                                 field[length] == ':') {
294                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
295                                 continue;
296                         }
297                         if (*p == '+') {
298                                 /* forwarded message */
299                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
300                         } else {
301                                 make_mime_composition_file_entry(p);
302                         }
303                 }
304         }
305
306         fclose(composition_file);
307
308         /*
309         ** We're ready to roll!  Run mhbuild on the composition file.
310         ** Note that mhbuild is in the context as buildmimeproc.
311         */
312         sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
313
314         if (system(buf) != 0) {
315                 clean_up_temporary_files();
316                 return (NOTOK);
317         }
318
319         return (OK);
320 }
321
322 static void
323 clean_up_temporary_files(void)
324 {
325         unlink(body_file_name);
326         unlink(composition_file_name);
327
328         return;
329 }
330
331 static int
332 get_line(void)
333 {
334         int c;  /* current character */
335         int n;  /* number of bytes in buffer */
336         char *p;  /* buffer pointer */
337
338         /*
339         ** Get a line from the input file, growing the field buffer as
340         ** needed.  We do this so that we can fit an entire line in the
341         ** buffer making it easy to do a string comparison on both the
342         ** field name and the field body which might be a long path name.
343         */
344
345         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
346                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
347                         ungetc(c, draft_file);
348                         c = '\n';
349                         break;
350                 }
351
352                 if (++n >= field_size - 1) {
353                         field = (char *)mh_xrealloc((void *)field, field_size += 256);
354
355                         p = field + n - 1;
356                 }
357         }
358
359         /* NUL-terminate the field. */
360         *p = '\0';
361
362         return (c);
363 }
364
365 static void
366 make_mime_composition_file_entry(char *file_name)
367 {
368         int binary;  /* binary character found flag */
369         int c;  /* current character */
370         char *content_type;  /* mime content type */
371         FILE *fp;  /* content and pipe file pointer */
372         struct node *np;  /* context scan node pointer */
373         char *p;  /* miscellaneous string pointer */
374
375         content_type = NULL;
376
377         
378         /*
379         ** Check the file name for a suffix.  Scan the context for that
380         ** suffix on a mhshow-suffix- entry.  We use these entries to
381         ** be compatible with mhshow, and there's no reason to make the
382         ** user specify each suffix twice.  Context entries of the form
383         ** "mhshow-suffix-contenttype" in the name have the suffix in
384         ** the field, including the dot.
385         */
386
387         if ((p = strrchr(file_name, '.')) != NULL) {
388                 for (np = m_defs; np; np = np->n_next) {
389                         if (strncasecmp(np->n_name, "mhshow-suffix-", 14) == 0
390                                         && mh_strcasecmp(p, np->n_field) == 0)
391                                         {
392                                 content_type = np->n_name + 14;
393                                 break;
394                         }
395                 }
396         }
397
398         /*
399         ** No content type was found, either because there was no matching
400         ** entry in the context or because the file name has no suffix.
401         ** Open the file and check for non-ASCII characters.  Choose the
402         ** content type based on this check.
403         */
404
405         if (content_type == NULL) {
406                 if ((fp = fopen(file_name, "r")) == (FILE *)0) {
407                         clean_up_temporary_files();
408                         adios(NULL, "unable to access file \"%s\"",
409                                         file_name);
410                 }
411
412                 binary = 0;
413
414                 while ((c = getc(fp)) != EOF) {
415                         if (c > 127 || c < 0) {
416                                 binary = 1;
417                                 break;
418                         }
419                 }
420
421                 fclose(fp);
422
423                 content_type = binary ?
424                                 "application/octet-stream" : "text/plain";
425         }
426
427         /*
428         ** Make sure that the attachment file exists and is readable.
429         ** Append a mhbuild directive to the draft file.  This starts with
430         ** the content type.  Append a file name attribute and a private
431         ** x-unix-mode attribute.  Also append a description obtained
432         ** (if possible) by running the "file" command on the file.
433         */
434
435         if (access(file_name, R_OK) != 0) {
436                 clean_up_temporary_files();
437                 adios(NULL, "unable to access file \"%s\"", file_name);
438         }
439
440
441         if (stringdex(toabsdir(invo_name), file_name) == 0) {
442                 /*
443                 ** Content had been placed by send into a temp file.
444                 ** Don't generate Content-Disposition header, because
445                 ** it confuses Microsoft Outlook, Build 10.0.6626, at
446                 ** least.
447                 */
448                 fprintf(composition_file, "#%s <>", content_type);
449         } else {
450                 /*
451                 ** Suppress Content-Id, insert simple
452                 ** Content-Disposition.
453                 */
454                 fprintf(composition_file,
455                         "#%s; name=\"%s\" <>{attachment}",
456                         content_type,
457                         ((p = strrchr(file_name, '/')) == NULL) ?
458                         file_name : p + 1);
459         }
460
461         /* Finish up with the file name. */
462         fprintf(composition_file, " %s\n", file_name);
463
464         return;
465 }
466
467 /*
468 ** Annotate original message, and
469 ** call `postproc' to send message.
470 */
471
472 static int
473 sendaux(char **vec, int vecp, char *drft, struct stat *st)
474 {
475         pid_t child_id;
476         int i, status, fd, fd2;
477         char backup[BUFSIZ];
478
479         fd = pushsw ? tmp_fd() : NOTOK;
480         fd2 = NOTOK;
481
482         vec[vecp++] = drft;
483         if (annotext && (fd2 = tmp_fd()) == NOTOK) {
484                 admonish(NULL, "unable to create file for annotation list");
485         }
486         if (distfile && distout(drft, distfile, backup) == NOTOK)
487                 done(1);
488         vec[vecp] = NULL;
489
490         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
491                 sleep(5);
492
493         switch (child_id) {
494         case -1:
495                 /* oops -- fork error */
496                 adios("fork", "unable to");
497                 break;  /* NOT REACHED */
498
499         case 0:
500                 /*
501                 ** child process -- send it
502                 **
503                 ** If fd is ok, then we are pushing and fd points to temp
504                 ** file, so capture anything on stdout and stderr there.
505                 */
506                 if (fd != NOTOK) {
507                         dup2(fd, fileno(stdout));
508                         dup2(fd, fileno(stderr));
509                         close(fd);
510                 }
511                 execvp(postproc, vec);
512                 fprintf(stderr, "unable to exec ");
513                 perror(postproc);
514                 _exit(-1);
515                 break;  /* NOT REACHED */
516
517         default:
518                 /*
519                 ** parent process -- wait for it
520                 */
521                 if ((status = pidwait(child_id, NOTOK)) == OK) {
522                         if (annotext && fd2 != NOTOK)
523                                 anno(fd2, st);
524                 } else {
525                         /*
526                         ** If postproc failed, and we have good fd (which
527                         ** means we pushed), then mail error message
528                         ** (and possibly the draft) back to the user.
529                         */
530                         if (fd != NOTOK) {
531                                 alert(drft, fd);
532                                 close(fd);
533                         } else {
534                                 advise(NULL, "message not delivered to anyone");
535                         }
536                         if (annotext && fd2 != NOTOK)
537                                 close(fd2);
538                         if (distfile) {
539                                 unlink(drft);
540                                 if (rename(backup, drft) == NOTOK)
541                                         advise(drft, "unable to rename %s to",
542                                                         backup);
543                         }
544                 }
545                 break;
546         }
547
548         return status;
549 }
550
551
552 /*
553 ** Mail error notification (and possibly a copy of the
554 ** message) back to the user, using the mailproc
555 */
556
557 static void
558 alert(char *file, int out)
559 {
560         pid_t child_id;
561         int i, in;
562         char buf[BUFSIZ];
563
564         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
565                 sleep(5);
566
567         switch (child_id) {
568         case NOTOK:
569                 /* oops -- fork error */
570                 advise("fork", "unable to");
571
572         case OK:
573                 /* child process -- send it */
574                 SIGNAL(SIGHUP, SIG_IGN);
575                 SIGNAL(SIGINT, SIG_IGN);
576                 SIGNAL(SIGQUIT, SIG_IGN);
577                 SIGNAL(SIGTERM, SIG_IGN);
578                 if (forwsw) {
579                         if ((in = open(file, O_RDONLY)) == NOTOK) {
580                                 admonish(file, "unable to re-open");
581                         } else {
582                                 lseek(out, (off_t) 0, SEEK_END);
583                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
584                                 write(out, buf, strlen(buf));
585                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
586                                 write(out, buf, strlen(buf));
587                                 cpydgst(in, out, file, "temporary file");
588                                 close(in);
589                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
590                                 write(out, buf, strlen(buf));
591                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
592                                         admonish(buf, "unable to rename %s to", file);
593                         }
594                 }
595                 lseek(out, (off_t) 0, SEEK_SET);
596                 dup2(out, fileno(stdin));
597                 close(out);
598                 /* create subject for error notification */
599                 snprintf(buf, sizeof(buf), "send failed on %s",
600                                 forwsw ? "enclosed draft" : file);
601
602                 execlp(mailproc, mhbasename(mailproc), getusername(),
603                                 "-subject", buf, NULL);
604                 fprintf(stderr, "unable to exec ");
605                 perror(mailproc);
606                 _exit(-1);
607
608         default:  /* no waiting... */
609                 break;
610         }
611 }
612
613
614 static int
615 tmp_fd(void)
616 {
617         int fd;
618         char *tfile = NULL;
619
620         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
621         if (tfile == NULL) return NOTOK;
622         fchmod(fd, 0600);
623
624         if (debugsw)
625                 advise(NULL, "temporary file %s selected", tfile);
626         else
627                 if (unlink(tfile) == NOTOK)
628                         advise(tfile, "unable to remove");
629
630         return fd;
631 }
632
633
634 static void
635 anno(int fd, struct stat *st)
636 {
637         pid_t child_id;
638         sigset_t set, oset;
639         static char *cwd = NULL;
640         struct stat st2;
641
642         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
643                         st->st_mtime != st2.st_mtime ||
644                         st->st_dev != st2.st_dev ||
645                         st->st_ino != st2.st_ino)) {
646                 if (debugsw)
647                         admonish(NULL, "$mhaltmsg mismatch");
648                 return;
649         }
650
651         child_id = debugsw ? NOTOK : fork();
652         switch (child_id) {
653         case NOTOK:  /* oops */
654                 if (!debugsw)
655                         advise(NULL, "unable to fork, so doing annotations by hand...");
656                 if (cwd == NULL)
657                         cwd = getcpy(pwd());
658
659         case OK:
660                 /* block a few signals */
661                 sigemptyset(&set);
662                 sigaddset(&set, SIGHUP);
663                 sigaddset(&set, SIGINT);
664                 sigaddset(&set, SIGQUIT);
665                 sigaddset(&set, SIGTERM);
666                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
667
668                 annoaux(fd);
669                 if (child_id == OK)
670                         _exit(0);
671
672                 /* reset the signal mask */
673                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
674
675                 chdir(cwd);
676                 break;
677
678         default:  /* no waiting... */
679                 close(fd);
680                 break;
681         }
682 }
683
684
685 static void
686 annoaux(int fd)
687 {
688         int fd2, fd3, msgnum;
689         char *cp, *folder, *maildir;
690         char buffer[BUFSIZ], **ap;
691         FILE *fp;
692         struct msgs *mp;
693
694         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
695                 if (debugsw)
696                         admonish(NULL, "$mhfolder not set");
697                 return;
698         }
699         maildir = toabsdir(folder);
700         if (chdir(maildir) == NOTOK) {
701                 if (debugsw)
702                         admonish(maildir, "unable to change directory to");
703                 return;
704         }
705         if (!(mp = folder_read(folder))) {
706                 if (debugsw)
707                         admonish(NULL, "unable to read folder %s", folder);
708                 return;
709         }
710
711         /* check for empty folder */
712         if (mp->nummsg == 0) {
713                 if (debugsw)
714                         admonish(NULL, "no messages in %s", folder);
715                 goto oops;
716         }
717
718         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
719                 if (debugsw)
720                         admonish(NULL, "$mhmessages not set");
721                 goto oops;
722         }
723         if (!debugsw  /* MOBY HACK... */
724                         && pushsw
725                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
726                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
727                 dup2(fd3, fileno(stderr));
728                 close(fd3);
729         }
730         else
731                 fd2 = NOTOK;
732         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
733                 m_convert(mp, *ap);
734         free(cp);
735         if (fd2 != NOTOK)
736                 dup2(fd2, fileno(stderr));
737         if (mp->numsel == 0) {
738                 if (debugsw)
739                         admonish(NULL, "no messages to annotate");
740                 goto oops;
741         }
742
743         lseek(fd, (off_t) 0, SEEK_SET);
744         if ((fp = fdopen(fd, "r")) == NULL) {
745                 if (debugsw)
746                         admonish(NULL, "unable to fdopen annotation list");
747                 goto oops;
748         }
749         cp = NULL;
750         while (fgets(buffer, sizeof(buffer), fp) != NULL)
751                 cp = add(buffer, cp);
752         fclose(fp);
753
754         if (debugsw)
755                 advise(NULL, "annotate%s with %s: \"%s\"",
756                                 inplace ? " inplace" : "", annotext, cp);
757         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
758                 if (is_selected(mp, msgnum)) {
759                         if (debugsw)
760                                 advise(NULL, "annotate message %d", msgnum);
761                         annotate(m_name(msgnum), annotext, cp, inplace,
762                                         1, -2, 0);
763                 }
764         }
765
766         free(cp);
767
768 oops:
769         folder_free(mp);  /* free folder/message structure */
770 }
771
772
773 static void
774 armed_done(int status)
775 {
776         longjmp(env, status ? status : NOTOK);
777
778         exit(status);
779 }