send: MIMEify with non-ascii header and ascii body!
[mmh] / uip / send.c
1 /*
2 ** send.c -- send a composed message
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 <fcntl.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <h/signals.h>
14 #include <h/mime.h>
15 #include <h/tws.h>
16 #include <h/utils.h>
17 #include <sysexits.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 #include <ctype.h>
21 #include <sys/stat.h>
22 #include <locale.h>
23
24 #ifdef HAVE_SYS_TIME_H
25 # include <sys/time.h>
26 #endif
27 #include <time.h>
28
29 #ifdef HAVE_SYS_PARAM_H
30 # include <sys/param.h>
31 #endif
32
33 int debugsw = 0;  /* global */
34 char *altmsg = NULL;
35 char *annotext = NULL;
36 char *distfile = NULL;
37
38 /* name of temp file for body content */
39 static char body_file_name[MAXPATHLEN + 1];
40 /* name of mhbuild composition temporary file */
41 static char composition_file_name[MAXPATHLEN + 1]; 
42 static int field_size;  /* size of header field buffer */
43 static char *field;  /* header field buffer */
44 static FILE *draft_file;  /* draft file pointer */
45 static FILE *body_file;  /* body file pointer */
46 static FILE *composition_file;  /* composition file pointer */
47
48 /*
49 ** static prototypes
50 */
51 static int sendsbr(char **, int, char *, struct stat *);
52 static void anno(struct stat *);
53 static int sendaux(char **, int, char *, struct stat *);
54 static int attach(char *);
55 static int signandenc(char *);
56 static void clean_up_temporary_files(void);
57 static int get_line(void);
58 static void make_mime_composition_file_entry(char *);
59 static char* strexit(int status);
60
61
62 static struct swit switches[] = {
63 #define DEBUGSW  0
64         { "debug", -5 },
65 #define VERBSW  1
66         { "verbose", 0 },
67 #define NVERBSW  2
68         { "noverbose", 2 },
69 #define VERSIONSW  3
70         { "Version", 0 },
71 #define HELPSW  4
72         { "help", 0 },
73         { NULL, 0 }
74 };
75
76
77 int
78 main(int argc, char **argv)
79 {
80         int nmsgs = 0, nfiles = 0, distsw = 0, vecp = 1;
81         int msgnum, status;
82         int in, out;
83         int n;
84         char *cp, *maildir = NULL;
85         char buf[BUFSIZ], **argp, **arguments;
86         char *msgs[MAXARGS], *vec[MAXARGS];
87         char *files[MAXARGS];
88         struct msgs *mp;
89         struct stat st;
90         struct stat st2;
91
92         setlocale(LC_ALL, "");
93         invo_name = mhbasename(argv[0]);
94
95         /* read user profile/context */
96         context_read();
97
98         arguments = getarguments(invo_name, argc, argv, 1);
99         argp = arguments;
100
101         while ((cp = *argp++)) {
102                 if (*cp == '-') {
103                         switch (smatch(++cp, switches)) {
104                         case AMBIGSW:
105                                 ambigsw(cp, switches);
106                                 exit(EX_USAGE);
107                         case UNKWNSW:
108                                 adios(EX_USAGE, NULL, "-%s unknown\n", cp);
109
110                         case HELPSW:
111                                 snprintf(buf, sizeof(buf),
112                                                 "%s [file] [switches]",
113                                                 invo_name);
114                                 print_help(buf, switches, 1);
115                                 exit(argc == 2 ? EX_OK : EX_USAGE);
116                         case VERSIONSW:
117                                 print_version(invo_name);
118                                 exit(argc == 2 ? EX_OK : EX_USAGE);
119
120                         case DEBUGSW:
121                                 debugsw++;
122                                 /* fall */
123                         case VERBSW:
124                         case NVERBSW:
125                                 vec[vecp++] = --cp;
126                                 continue;
127                         }
128                 } else {
129                         if (*cp == '/') {
130                                 files[nfiles++] = cp;
131                         } else {
132                                 msgs[nmsgs++] = cp;
133                         }
134                 }
135         }
136
137         if (!nmsgs && !nfiles) {
138                 msgs[nmsgs++] = seq_cur;
139         }
140
141         if (nmsgs) {
142                 maildir = toabsdir(draftfolder);
143                 if (chdir(maildir) == NOTOK) {
144                         adios(EX_OSERR, maildir, "unable to change directory to");
145                 }
146                 if (!(mp = folder_read(draftfolder))) {
147                         adios(EX_IOERR, NULL, "unable to read draft folder %s",
148                                         draftfolder);
149                 }
150                 if (mp->nummsg == 0) {
151                         adios(EX_DATAERR, NULL, "no messages in draft folder %s",
152                                         draftfolder);
153                 }
154                 /* parse all the msgranges/sequences and set SELECTED */
155                 for (msgnum = 0; msgnum < nmsgs; msgnum++) {
156                         if (!m_convert(mp, msgs[msgnum])) {
157                                 exit(EX_USAGE);
158                         }
159                 }
160                 seq_setprev(mp);
161
162                 for (nmsgs = 0, msgnum = mp->lowsel;
163                                 msgnum <= mp->hghsel; msgnum++) {
164                         if (is_selected(mp, msgnum)) {
165                                 files[nfiles++] = getcpy(m_name(msgnum));
166                                 unset_exists(mp, msgnum);
167                         }
168                 }
169
170                 mp->msgflags |= SEQMOD;
171                 seq_save(mp);
172         }
173
174         if (!(cp = getenv("SIGNATURE")) || !*cp) {
175                 if ((cp = context_find("signature")) && *cp) {
176                         m_putenv("SIGNATURE", cp);
177                 }
178         }
179
180         for (n = 0; n < nfiles; n++) {
181                 if (stat(files[n], &st) == NOTOK) {
182                         adios(EX_IOERR, files[n], "unable to stat draft file");
183                 }
184         }
185
186         if (!(annotext = getenv("mhannotate")) || !*annotext) {
187                 annotext = NULL;
188         }
189         if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
190                 altmsg = NULL;  /* used by dist interface - see below */
191         }
192
193         if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
194                 vec[vecp++] = "-dist";
195                 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
196                         adios(EX_IOERR, altmsg, "unable to open for reading");
197                 }
198                 fstat(in, &st2);
199                 distfile = getcpy(m_mktemp2(NULL, invo_name, NULL, NULL));
200                 if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
201                         adios(EX_IOERR, distfile, "unable to open for writing");
202                 }
203                 cpydata(in, out, altmsg, distfile);
204                 close(in);
205                 close(out);
206         } else {
207                 distfile = NULL;
208         }
209
210         if (!altmsg || stat(altmsg, &st) == NOTOK) {
211                 st.st_mtime = 0;
212                 st.st_dev = 0;
213                 st.st_ino = 0;
214         }
215         status = 0;
216         vec[0] = "spost";
217         for (n=3; n<OPEN_MAX; n++) {
218                 close(n);
219         }
220
221         for (n = 0; n < nfiles; n++) {
222                 switch (sendsbr(vec, vecp, files[n], &st)) {
223                 case DONE:
224                         exit(++status);
225                 case NOTOK:
226                         status++;  /* fall */
227                 case OK:
228                         break;
229                 }
230         }
231
232         context_save();
233         return status;
234 }
235
236
237 /*
238 ** message sending back-end
239 */
240 static int
241 sendsbr(char **vec, int vecp, char *drft, struct stat *st)
242 {
243         int status, dupfd;
244         char *original_draft;
245
246         /*
247         ** Save the original name of the draft file.  The name of the
248         ** draft file is changed to a temporary file containing the built
249         ** MIME message if there are attachments.  We need the original
250         ** name so that it can be renamed after the message is sent.
251         */
252         original_draft = drft;
253
254         /*
255         ** Convert the draft to a MIME message.
256         ** Use the mhbuild composition file for the draft if there was
257         ** a successful conversion because that now contains the MIME
258         ** message.  A nice side effect of this is that it leaves the
259         ** original draft file untouched so that it can be retrieved
260         ** and modified if desired.
261         */
262         switch (attach(drft)) {
263         case OK:
264                 drft = composition_file_name;
265                 break;
266
267         case NOTOK:
268                 return (NOTOK);
269
270         case DONE:
271                 break;
272         }
273
274         /*
275         ** Sign and encrypt the message as needed.
276         ** Use the mhbuild composition file for the draft if there was
277         ** a successful conversion because that now contains the MIME
278         ** message.  A nice side effect of this is that it leaves the
279         ** original draft file untouched so that it can be retrieved
280         ** and modified if desired.
281         */
282         switch (signandenc(drft)) {
283         case OK:
284                 drft = composition_file_name;
285                 break;
286
287         case NOTOK:
288                 return (NOTOK);
289
290         case DONE:
291                 break;
292         }
293
294         if ((status = sendaux(vec, vecp, drft, st)) == OK) {
295                 /* move original draft to +trash folder */
296                 /* temporary close stdin, for refile not to ask */
297                 dupfd = dup(0);
298                 close(0);
299                 if (execprogl("refile", "refile", "-file",
300                                 original_draft, "+trash",
301                                 (char *)NULL) != 0) {
302                         advise(NULL, "unable to trash the draft");
303                 }
304                 dup2(dupfd, 0);
305                 close(dupfd);
306         } else {
307                 status = DONE;
308         }
309
310         if (distfile) {
311                 unlink(distfile);
312         }
313
314         /* Get rid of temporary files that we created for attachments. */
315         if (drft == composition_file_name) {
316                 clean_up_temporary_files();
317         }
318
319         return status;
320 }
321
322 static int
323 contains_non_ascii(char *str)
324 {
325         char *cp;
326
327         for (cp = str; *cp; cp++) {
328                 if (*cp > 127 || *cp < 0) {
329                         return 1;
330                 }
331         }
332         return 0;
333 }
334
335 static int
336 attach(char *draft_file_name)
337 {
338         char buf[MAXPATHLEN + 6];
339         int c;
340         int has_attachment;
341         int has_body = 0;
342         int non_ascii = 0; /* msg body or hdr contains non-ASCII chars */
343         int length;  /* length of attachment header field name */
344         char *p;
345
346         if (!(draft_file = fopen(draft_file_name, "r"))) {
347                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
348         }
349
350         /* We'll grow the buffer as needed. */
351         field = (char *)mh_xmalloc(field_size = 256);
352
353         /*
354         ** Scan the draft file for an attachment header field name.
355         */
356         length = strlen(attach_hdr);
357         has_attachment = 0;
358         while (get_line() != EOF && *field != '\0' && *field != '-') {
359                 if (strncasecmp(field, attach_hdr, length)==0 &&
360                                 field[length] == ':') {
361                         has_attachment = 1;
362                 }
363                 if (contains_non_ascii(field)) {
364                         non_ascii = 1;
365                 }
366         }
367
368         /*
369         ** Look for at least one non-blank line in the body of the
370         ** message which indicates content in the body.
371         ** Check if body contains at least one non-blank (= not empty)
372         ** and if it contains any non-ASCII chars (= need MIME).
373         */
374         while (get_line() != EOF) {
375                 if (contains_non_ascii(field)) {
376                         non_ascii = 1;
377                 }
378                 for (p = field; *p; p++) {
379                         if (isgraph(*p)) {
380                                 has_body = 1;
381                         }
382                 }
383                 if (has_body && non_ascii) {
384                         break;  /* that's been already enough information */
385                 }
386         }
387
388         if (!has_attachment && non_ascii==0) {
389                 /* We don't need to convert it to MIME. */
390                 return DONE;
391         }
392
393         /*
394         ** Else: mimify
395         */
396
397         /* Make names for the temporary files.  */
398         strncpy(body_file_name,
399                         m_mktemp(toabsdir(invo_name), NULL, NULL),
400                         sizeof (body_file_name));
401         strncpy(composition_file_name,
402                         m_mktemp(toabsdir(invo_name), NULL, NULL),
403                         sizeof (composition_file_name));
404
405         if (has_body) {
406                 body_file = fopen(body_file_name, "w");
407         }
408         composition_file = fopen(composition_file_name, "w");
409
410         if ((has_body && !body_file) || !composition_file) {
411                 clean_up_temporary_files();
412                 adios(EX_IOERR, NULL, "unable to open all of the temporary files.");
413         }
414
415         /* Copy non-attachment header fields to the temp composition file. */
416         rewind(draft_file);
417         while (get_line() != EOF && *field && *field != '-') {
418                 if (strncasecmp(field, attach_hdr, length) != 0 ||
419                                 field[length] != ':') {
420                         fprintf(composition_file, "%s\n", field);
421                 }
422         }
423         fputs("--------\n", composition_file);
424
425         if (has_body) {
426                 /* Copy the message body to the temporary file. */
427                 while ((c = getc(draft_file)) != EOF) {
428                         putc(c, body_file);
429                 }
430                 fclose(body_file);
431
432                 /* Add a mhbuild MIME composition file line for the body */
433                 /* charset will be discovered/guessed by mhbuild */
434                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
435         }
436
437         /*
438         ** Now, go back to the beginning of the draft file and look for
439         ** header fields that specify attachments.  Add a mhbuild MIME
440         ** composition file for each.
441         */
442         rewind(draft_file);
443         while (get_line() != EOF && *field && *field != '-') {
444                 if (strncasecmp(field, attach_hdr, length) == 0 &&
445                                 field[length] == ':') {
446                         p = trim(field+length+1);
447                         if (*p == '+') {
448                                 /* forwarded message */
449                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
450                         } else {
451                                 /* regular attachment */
452                                 make_mime_composition_file_entry(p);
453                         }
454                 }
455         }
456         fclose(composition_file);
457
458         /* We're ready to roll! */
459         if (execprogl("mhbuild", "mhbuild", composition_file_name,
460                         (char *)NULL) != 0) {
461                 /* some problem */
462                 clean_up_temporary_files();
463                 return (NOTOK);
464         }
465         /* Remove the automatically created backup of mhbuild. */
466         snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
467         if (unlink(buf) == -1) {
468                 advise(NULL, "unable to remove original composition file.");
469         }
470
471         return (OK);
472 }
473
474 static int
475 signandenc(char *draft_file_name)
476 {
477         char buf[BUFSIZ];
478         int dosign = 0;
479         int doenc = 0;
480         int ret;
481
482         if (!(draft_file = fopen(draft_file_name, "r"))) {
483                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
484         }
485
486         /* We'll grow the buffer as needed. */
487         field = (char *)mh_xmalloc(field_size = 256);
488
489         /* Scan the draft file for an attachment header field name. */
490         while (get_line() != EOF && *field != '\0' && *field != '-') {
491                 if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
492                                 field[strlen(sign_hdr)] == ':') {
493                         dosign = 1;
494                 }
495                 if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
496                                 field[strlen(enc_hdr)] == ':') {
497                         doenc = 1;
498                 }
499         }
500         if (!dosign && !doenc) {
501                 return DONE;
502         }
503
504         strcpy(composition_file_name, draft_file_name);
505
506         /* We're ready to roll! */
507         if (doenc) {
508                 ret = execprogl("mhsign", "mhsign", "-m", "-e",
509                                 draft_file_name, (char *)NULL);
510         } else {
511                 ret = execprogl("mhsign", "mhsign", "-m",
512                                 draft_file_name, (char *)NULL);
513         }
514         if (ret != 0) {
515                 /* some problem */
516                 return (NOTOK);
517         }
518         /* Remove the automatically created backup of mhsign. */
519         snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
520         if (unlink(buf) == -1) {
521                 advise(NULL, "unable to remove original draft file.");
522         }
523
524         return (OK);
525 }
526
527 static void
528 clean_up_temporary_files(void)
529 {
530         unlink(body_file_name);
531         unlink(composition_file_name);
532
533         return;
534 }
535
536 static int
537 get_line(void)
538 {
539         int c;  /* current character */
540         int n;  /* number of bytes in buffer */
541         char *p;
542
543         /*
544         ** Get a line from the input file, growing the field buffer as
545         ** needed.  We do this so that we can fit an entire line in the
546         ** buffer making it easy to do a string comparison on both the
547         ** field name and the field body which might be a long path name.
548         */
549         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
550                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
551                         ungetc(c, draft_file);
552                         c = '\n';
553                         break;
554                 }
555                 if (++n >= field_size - 1) {
556                         field = (char *)mh_xrealloc(field, field_size += 256);
557                         p = field + n - 1;
558                 }
559         }
560         *p = '\0';
561
562         return (c);
563 }
564
565 static void
566 make_mime_composition_file_entry(char *file_name)
567 {
568         FILE *fp;
569         struct node *np;
570         char *cp;
571         char content_type[BUFSIZ];
572         char cmdbuf[BUFSIZ];
573         char *cmd = mimetypequeryproc;
574         int semicolon = 0;
575
576         for (np = m_defs; np; np = np->n_next) {
577                 if (strcasecmp(np->n_name, mimetypequery)==0) {
578                         cmd = np->n_field;
579                         break;
580                 }
581         }
582         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
583
584         if (!(fp = popen(cmdbuf, "r"))) {
585                 clean_up_temporary_files();
586                 adios(EX_IOERR, NULL, "unable to determine content type with `%s'",
587                                 cmdbuf);
588         }
589         if (fgets(content_type, sizeof content_type, fp) &&
590                         (cp = strrchr(content_type, '\n'))) {
591                 *cp = '\0';
592         } else {
593                 strcpy(content_type, "application/octet-stream");
594                 admonish(NULL, "problems with `%s', using fall back type `%s'",
595                                 cmdbuf, content_type);
596         }
597         pclose(fp);
598
599         /* TODO: don't use access(2) because it checks for ruid, not euid */
600         if (access(file_name, R_OK) != 0) {
601                 clean_up_temporary_files();
602                 adios(EX_IOERR, NULL, "unable to access file `%s'", file_name);
603         }
604
605         /* Check for broken file(1). See man page mh-profile(5). */
606         for (cp=content_type; *cp; cp++) {
607                 if (isspace(*cp)) {
608                         if (!semicolon) {
609                                 adios(EX_SOFTWARE, NULL, "Sorry, your Mime-Type-Query command (%s) is broken.\n\tThe output misses a semicolon before the whitespace.\n\tOutput was: %s", cmd, content_type);
610                         }
611                 } else if (*cp == ';') {
612                         semicolon = 1;
613                 } else {
614                         semicolon = 0;
615                 }
616         }
617
618         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
619         fprintf(composition_file,
620                         "#%s; name=\"%s\" <> [%s] {attachment} %s\n",
621                         content_type, cp, cp, file_name);
622
623         return;
624 }
625
626 /*
627 ** The back-end of the message sending back-end.
628 ** Annotate original message, and call `spost' to send message.
629 */
630 static int
631 sendaux(char **vec, int vecp, char *drft, struct stat *st)
632 {
633         pid_t child_id;
634         int status;
635         char backup[BUFSIZ];
636
637         vec[vecp++] = drft;
638         if (distfile && distout(drft, distfile, backup) == NOTOK) {
639                 return DONE;
640         }
641         vec[vecp] = NULL;
642
643         switch (child_id = fork()) {
644         case -1:
645                 /* oops -- fork error */
646                 advise("fork", "unable to");
647                 return DONE;
648
649         case 0:
650                 /* child process -- send it */
651                 execvp(*vec, vec);
652                 fprintf(stderr, "unable to exec ");
653                 perror(*vec);
654                 _exit(EX_OSERR);
655                 break;  /* NOT REACHED */
656
657         default:
658                 /* parent process -- wait for it */
659                 status = pidwait(child_id, NOTOK);
660                 if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
661                         if (annotext) {
662                                 anno(st);
663                         }
664                 } else {
665                         /* spost failed */
666                         advise(NULL, "%s", strexit(status));
667                         if (distfile) {
668                                 unlink(drft);
669                                 if (rename(backup, drft) == NOTOK) {
670                                         advise(drft, "unable to rename %s to",
671                                                         backup);
672                                 }
673                         }
674                 }
675         }
676
677
678         return status ? NOTOK : status;
679 }
680
681
682 static void
683 anno(struct stat *st)
684 {
685         struct stat st2;
686         char *msgs, *folder;
687         char buf[BUFSIZ];
688         char *vec[MAXARGS];
689         int vecp = 0;
690         char *cp, *dp;
691
692         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
693                         st->st_mtime != st2.st_mtime ||
694                         st->st_dev != st2.st_dev ||
695                         st->st_ino != st2.st_ino)) {
696                 if (debugsw) {
697                         admonish(NULL, "$mhaltmsg mismatch");
698                 }
699                 return;
700         }
701
702         if (!(folder = getenv("mhfolder")) || !*folder) {
703                 if (debugsw) {
704                         admonish(NULL, "$mhfolder not set");
705                 }
706                 return;
707         }
708         if (!(msgs = getenv("mhmessages")) || !*msgs) {
709                 if (debugsw) {
710                         admonish(NULL, "$mhmessages not set");
711                 }
712                 return;
713         }
714         if (debugsw) {
715                 advise(NULL, "annotate as `%s': %s %s", annotext,
716                                 folder, msgs);
717         }
718         vec[vecp++] = "anno";
719         vec[vecp++] = "-comp";
720         vec[vecp++] = annotext;
721         snprintf(buf, sizeof buf, "+%s", folder);
722         vec[vecp++] = buf;
723
724         while (isspace(*msgs)) {
725                 msgs++;
726         }
727         for (cp=dp=msgs; *cp; cp++) {
728                 if (isspace(*cp)) {
729                         while (isspace(*cp)) {
730                                 *cp++ = '\0';
731                         }
732                         vec[vecp++] = dp;
733                         dp = cp;
734                 }
735         }
736         vec[vecp++] = dp;
737         vec[vecp] = NULL;
738         if (execprog(*vec, vec) != 0) {
739                 advise(NULL, "unable to annotate");
740         }
741 }
742
743
744 char*
745 strexit(int status)
746 {
747         if (WIFSIGNALED(status)) {
748                 return "spost or sendmail killed by signal";
749         }
750         if (!WIFEXITED(status)) {
751                 return "message not delivered to anyone";
752         }
753         switch (WEXITSTATUS(status)) {
754         case EX_TEMPFAIL:
755                 return "Temporary error, maybe the MTA has queued the message";
756         default:
757                 return "message not delivered to anyone";
758         }
759 }