Removed the undocumented -unique switches. Seems they were JLR-only stuff.
[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], buf[BUFSIZ];
482
483         fd = pushsw ? tmp_fd() : NOTOK;
484         fd2 = NOTOK;
485
486         vec[vecp++] = drft;
487         if (annotext) {
488                 if ((fd2 = tmp_fd()) != NOTOK) {
489                         vec[vecp++] = "-idanno";
490                         snprintf(buf, sizeof(buf), "%d", fd2);
491                         vec[vecp++] = buf;
492                 } else {
493                         admonish(NULL, "unable to create file for annotation list");
494                 }
495         }
496         if (distfile && distout(drft, distfile, backup) == NOTOK)
497                 done(1);
498         vec[vecp] = NULL;
499
500         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
501                 sleep(5);
502
503         switch (child_id) {
504         case -1:
505                 /* oops -- fork error */
506                 adios("fork", "unable to");
507                 break;  /* NOT REACHED */
508
509         case 0:
510                 /*
511                 ** child process -- send it
512                 **
513                 ** If fd is ok, then we are pushing and fd points to temp
514                 ** file, so capture anything on stdout and stderr there.
515                 */
516                 if (fd != NOTOK) {
517                         dup2(fd, fileno(stdout));
518                         dup2(fd, fileno(stderr));
519                         close(fd);
520                 }
521                 execvp(postproc, vec);
522                 fprintf(stderr, "unable to exec ");
523                 perror(postproc);
524                 _exit(-1);
525                 break;  /* NOT REACHED */
526
527         default:
528                 /*
529                 ** parent process -- wait for it
530                 */
531                 if ((status = pidwait(child_id, NOTOK)) == OK) {
532                         if (annotext && fd2 != NOTOK)
533                                 anno(fd2, st);
534                 } else {
535                         /*
536                         ** If postproc failed, and we have good fd (which
537                         ** means we pushed), then mail error message
538                         ** (and possibly the draft) back to the user.
539                         */
540                         if (fd != NOTOK) {
541                                 alert(drft, fd);
542                                 close(fd);
543                         } else {
544                                 advise(NULL, "message not delivered to anyone");
545                         }
546                         if (annotext && fd2 != NOTOK)
547                                 close(fd2);
548                         if (distfile) {
549                                 unlink(drft);
550                                 if (rename(backup, drft) == NOTOK)
551                                         advise(drft, "unable to rename %s to",
552                                                         backup);
553                         }
554                 }
555                 break;
556         }
557
558         return status;
559 }
560
561
562 /*
563 ** Mail error notification (and possibly a copy of the
564 ** message) back to the user, using the mailproc
565 */
566
567 static void
568 alert(char *file, int out)
569 {
570         pid_t child_id;
571         int i, in;
572         char buf[BUFSIZ];
573
574         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
575                 sleep(5);
576
577         switch (child_id) {
578         case NOTOK:
579                 /* oops -- fork error */
580                 advise("fork", "unable to");
581
582         case OK:
583                 /* child process -- send it */
584                 SIGNAL(SIGHUP, SIG_IGN);
585                 SIGNAL(SIGINT, SIG_IGN);
586                 SIGNAL(SIGQUIT, SIG_IGN);
587                 SIGNAL(SIGTERM, SIG_IGN);
588                 if (forwsw) {
589                         if ((in = open(file, O_RDONLY)) == NOTOK) {
590                                 admonish(file, "unable to re-open");
591                         } else {
592                                 lseek(out, (off_t) 0, SEEK_END);
593                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
594                                 write(out, buf, strlen(buf));
595                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
596                                 write(out, buf, strlen(buf));
597                                 cpydgst(in, out, file, "temporary file");
598                                 close(in);
599                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
600                                 write(out, buf, strlen(buf));
601                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
602                                         admonish(buf, "unable to rename %s to", file);
603                         }
604                 }
605                 lseek(out, (off_t) 0, SEEK_SET);
606                 dup2(out, fileno(stdin));
607                 close(out);
608                 /* create subject for error notification */
609                 snprintf(buf, sizeof(buf), "send failed on %s",
610                                 forwsw ? "enclosed draft" : file);
611
612                 execlp(mailproc, mhbasename(mailproc), getusername(),
613                                 "-subject", buf, NULL);
614                 fprintf(stderr, "unable to exec ");
615                 perror(mailproc);
616                 _exit(-1);
617
618         default:  /* no waiting... */
619                 break;
620         }
621 }
622
623
624 static int
625 tmp_fd(void)
626 {
627         int fd;
628         char *tfile = NULL;
629
630         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
631         if (tfile == NULL) return NOTOK;
632         fchmod(fd, 0600);
633
634         if (debugsw)
635                 advise(NULL, "temporary file %s selected", tfile);
636         else
637                 if (unlink(tfile) == NOTOK)
638                         advise(tfile, "unable to remove");
639
640         return fd;
641 }
642
643
644 static void
645 anno(int fd, struct stat *st)
646 {
647         pid_t child_id;
648         sigset_t set, oset;
649         static char *cwd = NULL;
650         struct stat st2;
651
652         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
653                         st->st_mtime != st2.st_mtime ||
654                         st->st_dev != st2.st_dev ||
655                         st->st_ino != st2.st_ino)) {
656                 if (debugsw)
657                         admonish(NULL, "$mhaltmsg mismatch");
658                 return;
659         }
660
661         child_id = debugsw ? NOTOK : fork();
662         switch (child_id) {
663         case NOTOK:  /* oops */
664                 if (!debugsw)
665                         advise(NULL, "unable to fork, so doing annotations by hand...");
666                 if (cwd == NULL)
667                         cwd = getcpy(pwd());
668
669         case OK:
670                 /* block a few signals */
671                 sigemptyset(&set);
672                 sigaddset(&set, SIGHUP);
673                 sigaddset(&set, SIGINT);
674                 sigaddset(&set, SIGQUIT);
675                 sigaddset(&set, SIGTERM);
676                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
677
678                 annoaux(fd);
679                 if (child_id == OK)
680                         _exit(0);
681
682                 /* reset the signal mask */
683                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
684
685                 chdir(cwd);
686                 break;
687
688         default:  /* no waiting... */
689                 close(fd);
690                 break;
691         }
692 }
693
694
695 static void
696 annoaux(int fd)
697 {
698         int fd2, fd3, msgnum;
699         char *cp, *folder, *maildir;
700         char buffer[BUFSIZ], **ap;
701         FILE *fp;
702         struct msgs *mp;
703
704         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
705                 if (debugsw)
706                         admonish(NULL, "$mhfolder not set");
707                 return;
708         }
709         maildir = toabsdir(folder);
710         if (chdir(maildir) == NOTOK) {
711                 if (debugsw)
712                         admonish(maildir, "unable to change directory to");
713                 return;
714         }
715         if (!(mp = folder_read(folder))) {
716                 if (debugsw)
717                         admonish(NULL, "unable to read folder %s", folder);
718                 return;
719         }
720
721         /* check for empty folder */
722         if (mp->nummsg == 0) {
723                 if (debugsw)
724                         admonish(NULL, "no messages in %s", folder);
725                 goto oops;
726         }
727
728         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
729                 if (debugsw)
730                         admonish(NULL, "$mhmessages not set");
731                 goto oops;
732         }
733         if (!debugsw  /* MOBY HACK... */
734                         && pushsw
735                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
736                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
737                 dup2(fd3, fileno(stderr));
738                 close(fd3);
739         }
740         else
741                 fd2 = NOTOK;
742         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
743                 m_convert(mp, *ap);
744         free(cp);
745         if (fd2 != NOTOK)
746                 dup2(fd2, fileno(stderr));
747         if (mp->numsel == 0) {
748                 if (debugsw)
749                         admonish(NULL, "no messages to annotate");
750                 goto oops;
751         }
752
753         lseek(fd, (off_t) 0, SEEK_SET);
754         if ((fp = fdopen(fd, "r")) == NULL) {
755                 if (debugsw)
756                         admonish(NULL, "unable to fdopen annotation list");
757                 goto oops;
758         }
759         cp = NULL;
760         while (fgets(buffer, sizeof(buffer), fp) != NULL)
761                 cp = add(buffer, cp);
762         fclose(fp);
763
764         if (debugsw)
765                 advise(NULL, "annotate%s with %s: \"%s\"",
766                                 inplace ? " inplace" : "", annotext, cp);
767         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
768                 if (is_selected(mp, msgnum)) {
769                         if (debugsw)
770                                 advise(NULL, "annotate message %d", msgnum);
771                         annotate(m_name (msgnum), annotext, cp, inplace,
772                                         1, -2, 0);
773                 }
774         }
775
776         free(cp);
777
778 oops:
779         folder_free(mp);  /* free folder/message structure */
780 }
781
782
783 static void
784 armed_done(int status)
785 {
786         longjmp(env, status ? status : NOTOK);
787
788         exit(status);
789 }