send: Always MIMEify and pass already MIMIfied drafts through
[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, *folder = 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 if (*cp == '+' || *cp == '@') {
129                         if (folder) {
130                                 adios(EX_USAGE, NULL, "only one folder at a time!");
131                         } else {
132                                 folder = mh_xstrdup(expandfol(cp));
133                         }
134                 } else {
135                         if (*cp == '/') {
136                                 files[nfiles++] = cp;
137                         } else {
138                                 msgs[nmsgs++] = cp;
139                         }
140                 }
141         }
142
143         if (!nmsgs && !nfiles) {
144                 msgs[nmsgs++] = seq_cur;
145         }
146
147         if (nmsgs) {
148                 folder = folder ? folder : draftfolder;
149                 maildir = toabsdir(folder);
150                 if (chdir(maildir) == NOTOK) {
151                         adios(EX_OSERR, maildir, "unable to change directory to");
152                 }
153                 if (!(mp = folder_read(folder))) {
154                         adios(EX_IOERR, NULL, "unable to read folder %s",
155                                         folder);
156                 }
157                 if (mp->nummsg == 0) {
158                         adios(EX_DATAERR, NULL, "no messages in folder %s",
159                                         folder);
160                 }
161                 /* parse all the msgranges/sequences and set SELECTED */
162                 for (msgnum = 0; msgnum < nmsgs; msgnum++) {
163                         if (!m_convert(mp, msgs[msgnum])) {
164                                 exit(EX_USAGE);
165                         }
166                 }
167                 seq_setprev(mp);
168
169                 for (nmsgs = 0, msgnum = mp->lowsel;
170                                 msgnum <= mp->hghsel; msgnum++) {
171                         if (is_selected(mp, msgnum)) {
172                                 files[nfiles++] = mh_xstrdup(m_name(msgnum));
173                                 unset_exists(mp, msgnum);
174                         }
175                 }
176
177                 mp->msgflags |= SEQMOD;
178                 seq_save(mp);
179         }
180
181         if (!(cp = getenv("SIGNATURE")) || !*cp) {
182                 if ((cp = context_find("signature")) && *cp) {
183                         m_putenv("SIGNATURE", cp);
184                 }
185         }
186
187         for (n = 0; n < nfiles; n++) {
188                 if (stat(files[n], &st) == NOTOK) {
189                         adios(EX_IOERR, files[n], "unable to stat draft file");
190                 }
191         }
192
193         if (!(annotext = getenv("mhannotate")) || !*annotext) {
194                 annotext = NULL;
195         }
196         if (!(altmsg = getenv("mhaltmsg")) || !*altmsg) {
197                 altmsg = NULL;  /* used by dist interface - see below */
198         }
199
200         if ((cp = getenv("mhdist")) && *cp && (distsw = atoi(cp)) && altmsg) {
201                 vec[vecp++] = "-dist";
202                 if ((in = open(altmsg, O_RDONLY)) == NOTOK) {
203                         adios(EX_IOERR, altmsg, "unable to open for reading");
204                 }
205                 fstat(in, &st2);
206                 distfile = mh_xstrdup(m_mktemp2(NULL, invo_name, NULL, NULL));
207                 if ((out = creat(distfile, (int)st2.st_mode & 0777))==NOTOK) {
208                         adios(EX_IOERR, distfile, "unable to open for writing");
209                 }
210                 cpydata(in, out, altmsg, distfile);
211                 close(in);
212                 close(out);
213         } else {
214                 distfile = NULL;
215         }
216
217         if (!altmsg || stat(altmsg, &st) == NOTOK) {
218                 st.st_mtime = 0;
219                 st.st_dev = 0;
220                 st.st_ino = 0;
221         }
222         status = 0;
223         vec[0] = "spost";
224         for (n=3; n<OPEN_MAX; n++) {
225                 close(n);
226         }
227
228         for (n = 0; n < nfiles; n++) {
229                 switch (sendsbr(vec, vecp, files[n], &st)) {
230                 case DONE:
231                         exit(++status);
232                 case NOTOK:
233                         status++;  /* fall */
234                 case OK:
235                         break;
236                 }
237         }
238
239         context_save();
240         return status;
241 }
242
243
244 /*
245 ** message sending back-end
246 */
247 static int
248 sendsbr(char **vec, int vecp, char *drft, struct stat *st)
249 {
250         int status, dupfd;
251         char *original_draft;
252
253         /*
254         ** Save the original name of the draft file.  The name of the
255         ** draft file is changed to a temporary file containing the built
256         ** MIME message if there are attachments.  We need the original
257         ** name so that it can be renamed after the message is sent.
258         */
259         original_draft = drft;
260
261         /*
262         ** Convert the draft to a MIME message.
263         ** Use the mhbuild composition file for the draft if there was
264         ** a successful conversion because that now contains the MIME
265         ** message.  A nice side effect of this is that it leaves the
266         ** original draft file untouched so that it can be retrieved
267         ** and modified if desired.
268         */
269         switch (attach(drft)) {
270         case OK:
271                 /* successfully MIMEified: use generate draft */
272                 drft = composition_file_name;
273                 break;
274
275         case NOTOK:
276                 return (NOTOK);
277
278         case DONE:
279                 /* already in MIME format: keep original draft */
280                 break;
281         }
282
283         /*
284         ** Sign and encrypt the message as needed.
285         ** Use the mhbuild composition file for the draft if there was
286         ** a successful conversion because that now contains the MIME
287         ** message.  A nice side effect of this is that it leaves the
288         ** original draft file untouched so that it can be retrieved
289         ** and modified if desired.
290         */
291         switch (signandenc(drft)) {
292         case OK:
293                 drft = composition_file_name;
294                 break;
295
296         case NOTOK:
297                 return (NOTOK);
298
299         case DONE:
300                 break;
301         }
302
303         if ((status = sendaux(vec, vecp, drft, st)) == OK) {
304                 /* move original draft to +trash folder */
305                 /* temporary close stdin, for refile not to ask */
306                 dupfd = dup(0);
307                 close(0);
308                 if (execprogl("refile", "refile", "-file",
309                                 original_draft, "+trash",
310                                 (char *)NULL) != 0) {
311                         advise(NULL, "unable to trash the draft");
312                 }
313                 dup2(dupfd, 0);
314                 close(dupfd);
315         } else {
316                 status = DONE;
317         }
318
319         if (distfile) {
320                 unlink(distfile);
321         }
322
323         /* Get rid of temporary files that we created for attachments. */
324         if (drft == composition_file_name) {
325                 clean_up_temporary_files();
326         }
327
328         return status;
329 }
330
331 static int
332 attach(char *draft_file_name)
333 {
334         char buf[MAXPATHLEN + 6];
335         int c;
336         int length = strlen(attach_hdr);
337         char *p;
338
339         if (!(draft_file = fopen(draft_file_name, "r"))) {
340                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
341         }
342
343         /* We'll grow the buffer as needed. */
344         field = mh_xcalloc(field_size = 256, sizeof(char));
345
346         /*
347         ** MIMEify
348         */
349
350         /* Make names for the temporary files.  */
351         strncpy(body_file_name,
352                         m_mktemp(toabsdir(invo_name), NULL, NULL),
353                         sizeof (body_file_name));
354         strncpy(composition_file_name,
355                         m_mktemp(toabsdir(invo_name), NULL, NULL),
356                         sizeof (composition_file_name));
357
358         body_file = fopen(body_file_name, "w");
359         composition_file = fopen(composition_file_name, "w");
360
361         if (!body_file || !composition_file) {
362                 clean_up_temporary_files();
363                 adios(EX_IOERR, NULL, "unable to open all of the temporary files.");
364         }
365
366         /* Copy non-attachment header fields to the temp composition file. */
367         rewind(draft_file);
368         while (get_line() != EOF && *field && *field != '-') {
369                 if (strncasecmp(field, VRSN_FIELD, strlen(VRSN_FIELD))==0 &&
370                                 field[strlen(VRSN_FIELD)] == ':') {
371                         /*
372                         ** The draft is already in MIME format, thus
373                         ** back out and use the original draft file.
374                         */
375                         clean_up_temporary_files();
376                         return DONE;
377                 }
378
379                 if (strncasecmp(field, attach_hdr, length) != 0 ||
380                                 field[length] != ':') {
381                         fprintf(composition_file, "%s\n", field);
382                 }
383         }
384         fputs("--------\n", composition_file);
385
386         /* Copy the message body to the temporary file. */
387         while ((c = getc(draft_file)) != EOF) {
388                 putc(c, body_file);
389         }
390         fclose(body_file);
391
392         /* Add a mhbuild MIME composition file line for the body */
393         /* charset will be discovered/guessed by mhbuild */
394         fprintf(composition_file, "#text/plain %s\n", body_file_name);
395
396         /*
397         ** Now, go back to the beginning of the draft file and look for
398         ** header fields that specify attachments.  Add a mhbuild MIME
399         ** composition file for each.
400         */
401         rewind(draft_file);
402         while (get_line() != EOF && *field && *field != '-') {
403                 if (strncasecmp(field, attach_hdr, length) == 0 &&
404                                 field[length] == ':') {
405                         p = trim(field+length+1);
406                         if (*p == '+') {
407                                 /* forwarded message */
408                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
409                         } else {
410                                 /* regular attachment */
411                                 make_mime_composition_file_entry(p);
412                         }
413                 }
414         }
415         fclose(composition_file);
416
417         /* We're ready to roll! */
418         if (execprogl("mhbuild", "mhbuild", composition_file_name,
419                         (char *)NULL) != 0) {
420                 /* some problem */
421                 clean_up_temporary_files();
422                 return (NOTOK);
423         }
424         /* Remove the automatically created backup of mhbuild. */
425         snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
426         if (unlink(buf) == -1) {
427                 advise(NULL, "unable to remove original composition file.");
428         }
429
430         return (OK);
431 }
432
433 static int
434 signandenc(char *draft_file_name)
435 {
436         char buf[BUFSIZ];
437         int dosign = 0;
438         int doenc = 0;
439         int ret;
440
441         if (!(draft_file = fopen(draft_file_name, "r"))) {
442                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
443         }
444
445         /* We'll grow the buffer as needed. */
446         field = mh_xcalloc(field_size = 256, sizeof(char));
447
448         /* Scan the draft file for an attachment header field name. */
449         while (get_line() != EOF && *field != '\0' && *field != '-') {
450                 if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
451                                 field[strlen(sign_hdr)] == ':') {
452                         dosign = 1;
453                 }
454                 if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
455                                 field[strlen(enc_hdr)] == ':') {
456                         doenc = 1;
457                 }
458         }
459         if (!dosign && !doenc) {
460                 return DONE;
461         }
462
463         strcpy(composition_file_name, draft_file_name);
464
465         /* We're ready to roll! */
466         if (doenc) {
467                 ret = execprogl("mhsign", "mhsign", "-m", "-e",
468                                 draft_file_name, (char *)NULL);
469         } else {
470                 ret = execprogl("mhsign", "mhsign", "-m",
471                                 draft_file_name, (char *)NULL);
472         }
473         if (ret != 0) {
474                 /* some problem */
475                 return (NOTOK);
476         }
477         /* Remove the automatically created backup of mhsign. */
478         snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
479         if (unlink(buf) == -1) {
480                 advise(NULL, "unable to remove original draft file.");
481         }
482
483         return (OK);
484 }
485
486 static void
487 clean_up_temporary_files(void)
488 {
489         unlink(body_file_name);
490         unlink(composition_file_name);
491
492         return;
493 }
494
495 static int
496 get_line(void)
497 {
498         int c;  /* current character */
499         int n;  /* number of bytes in buffer */
500         char *p;
501
502         /*
503         ** Get a line from the input file, growing the field buffer as
504         ** needed.  We do this so that we can fit an entire line in the
505         ** buffer making it easy to do a string comparison on both the
506         ** field name and the field body which might be a long path name.
507         */
508         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
509                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
510                         ungetc(c, draft_file);
511                         c = '\n';
512                         break;
513                 }
514                 if (++n >= field_size - 1) {
515                         field = mh_xrealloc(field, field_size += 256);
516                         p = field + n - 1;
517                 }
518         }
519         *p = '\0';
520
521         return (c);
522 }
523
524 static void
525 make_mime_composition_file_entry(char *file_name)
526 {
527         FILE *fp;
528         struct node *np;
529         char *cp;
530         char content_type[BUFSIZ];
531         char cmdbuf[BUFSIZ];
532         char *cmd = mimetypequeryproc;
533         int semicolon = 0;
534
535         for (np = m_defs; np; np = np->n_next) {
536                 if (strcasecmp(np->n_name, mimetypequery)==0) {
537                         cmd = np->n_field;
538                         break;
539                 }
540         }
541         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
542
543         if (!(fp = popen(cmdbuf, "r"))) {
544                 clean_up_temporary_files();
545                 adios(EX_IOERR, NULL, "unable to determine content type with `%s'",
546                                 cmdbuf);
547         }
548         if (fgets(content_type, sizeof content_type, fp) &&
549                         (cp = strrchr(content_type, '\n'))) {
550                 *cp = '\0';
551         } else {
552                 strcpy(content_type, "application/octet-stream");
553                 admonish(NULL, "problems with `%s', using fall back type `%s'",
554                                 cmdbuf, content_type);
555         }
556         pclose(fp);
557
558         /* TODO: don't use access(2) because it checks for ruid, not euid */
559         if (access(file_name, R_OK) != 0) {
560                 clean_up_temporary_files();
561                 adios(EX_IOERR, NULL, "unable to access file `%s'", file_name);
562         }
563
564         /* Check for broken file(1). See man page mh-profile(5). */
565         for (cp=content_type; *cp; cp++) {
566                 if (isspace(*cp)) {
567                         if (!semicolon) {
568                                 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);
569                         }
570                 } else if (*cp == ';') {
571                         semicolon = 1;
572                 } else {
573                         semicolon = 0;
574                 }
575         }
576
577         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
578         fprintf(composition_file,
579                         "#%s; name=\"%s\" <> [%s] {attachment} %s\n",
580                         content_type, cp, cp, file_name);
581
582         return;
583 }
584
585 /*
586 ** The back-end of the message sending back-end.
587 ** Annotate original message, and call `spost' to send message.
588 */
589 static int
590 sendaux(char **vec, int vecp, char *drft, struct stat *st)
591 {
592         pid_t child_id;
593         int status;
594         char backup[BUFSIZ];
595
596         vec[vecp++] = drft;
597         if (distfile && distout(drft, distfile, backup) == NOTOK) {
598                 return DONE;
599         }
600         vec[vecp] = NULL;
601
602         switch (child_id = fork()) {
603         case -1:
604                 /* oops -- fork error */
605                 advise("fork", "unable to");
606                 return DONE;
607
608         case 0:
609                 /* child process -- send it */
610                 execvp(*vec, vec);
611                 fprintf(stderr, "unable to exec ");
612                 perror(*vec);
613                 _exit(EX_OSERR);
614                 break;  /* NOT REACHED */
615
616         default:
617                 /* parent process -- wait for it */
618                 status = pidwait(child_id, NOTOK);
619                 if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
620                         if (annotext) {
621                                 anno(st);
622                         }
623                 } else {
624                         /* spost failed */
625                         advise(NULL, "%s", strexit(status));
626                         if (distfile) {
627                                 unlink(drft);
628                                 if (rename(backup, drft) == NOTOK) {
629                                         advise(drft, "unable to rename %s to",
630                                                         backup);
631                                 }
632                         }
633                 }
634         }
635
636         return status ? NOTOK : status;
637 }
638
639
640 static void
641 anno(struct stat *st)
642 {
643         struct stat st2;
644         char *msgs, *folder;
645         char buf[BUFSIZ];
646         char *vec[MAXARGS];
647         int vecp = 0;
648         char *cp, *dp;
649
650         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
651                         st->st_mtime != st2.st_mtime ||
652                         st->st_dev != st2.st_dev ||
653                         st->st_ino != st2.st_ino)) {
654                 if (debugsw) {
655                         admonish(NULL, "$mhaltmsg mismatch");
656                 }
657                 return;
658         }
659
660         if (!(folder = getenv("mhfolder")) || !*folder) {
661                 if (debugsw) {
662                         admonish(NULL, "$mhfolder not set");
663                 }
664                 return;
665         }
666         if (!(msgs = getenv("mhmessages")) || !*msgs) {
667                 if (debugsw) {
668                         admonish(NULL, "$mhmessages not set");
669                 }
670                 return;
671         }
672         if (debugsw) {
673                 advise(NULL, "annotate as `%s': %s %s", annotext,
674                                 folder, msgs);
675         }
676         vec[vecp++] = "anno";
677         vec[vecp++] = "-comp";
678         vec[vecp++] = annotext;
679         snprintf(buf, sizeof buf, "+%s", folder);
680         vec[vecp++] = buf;
681
682         while (isspace(*msgs)) {
683                 msgs++;
684         }
685         for (cp=dp=msgs; *cp; cp++) {
686                 if (isspace(*cp)) {
687                         while (isspace(*cp)) {
688                                 *cp++ = '\0';
689                         }
690                         vec[vecp++] = dp;
691                         dp = cp;
692                 }
693         }
694         vec[vecp++] = dp;
695         vec[vecp] = NULL;
696         if (execprog(*vec, vec) != 0) {
697                 advise(NULL, "unable to annotate");
698         }
699 }
700
701
702 char*
703 strexit(int status)
704 {
705         if (WIFSIGNALED(status)) {
706                 return "spost or sendmail killed by signal";
707         }
708         if (!WIFEXITED(status)) {
709                 return "message not delivered to anyone";
710         }
711         switch (WEXITSTATUS(status)) {
712         case EX_TEMPFAIL:
713                 return "Temporary error, maybe the MTA has queued the message";
714         default:
715                 return "message not delivered to anyone";
716         }
717 }