ec9b76db4ca6bba70cecd4eb09c63b6607a7f534
[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 attach(char *draft_file_name)
324 {
325         char buf[MAXPATHLEN + 6];
326         int c;
327         int has_attachment;
328         int has_body;
329         int non_ascii; /* msg body contains non-ASCII chars */
330         int length;  /* length of attachment header field name */
331         char *p;
332
333         if (!(draft_file = fopen(draft_file_name, "r"))) {
334                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
335         }
336
337         /* We'll grow the buffer as needed. */
338         field = (char *)mh_xmalloc(field_size = 256);
339
340         /*
341         ** Scan the draft file for an attachment header field name.
342         */
343         length = strlen(attach_hdr);
344         has_attachment = 0;
345         while (get_line() != EOF && *field != '\0' && *field != '-') {
346                 if (strncasecmp(field, attach_hdr, length)==0 &&
347                                 field[length] == ':') {
348                         has_attachment = 1;
349                 }
350         }
351
352         /*
353         ** Look for at least one non-blank line in the body of the
354         ** message which indicates content in the body.
355         ** Check if body contains at least one non-blank (= not empty)
356         ** and if it contains any non-ASCII chars (= need MIME).
357         */
358         has_body = 0;
359         non_ascii = 0;
360         while (get_line() != EOF) {
361                 for (p = field; *p != '\0'; p++) {
362                         if (*p != ' ' && *p != '\t') {
363                                 has_body = 1;
364                         }
365                         if (*p > 127 || *p < 0) {
366                                 non_ascii = 1;
367                         }
368                 }
369                 if (has_body && non_ascii) {
370                         break;  /* that's been already enough information */
371                 }
372         }
373
374         if (!has_attachment && non_ascii==0) {
375                 /* We don't need to convert it to MIME. */
376                 return DONE;
377         }
378
379         /*
380         ** Else: mimify
381         */
382
383         /* Make names for the temporary files.  */
384         strncpy(body_file_name,
385                         m_mktemp(toabsdir(invo_name), NULL, NULL),
386                         sizeof (body_file_name));
387         strncpy(composition_file_name,
388                         m_mktemp(toabsdir(invo_name), NULL, NULL),
389                         sizeof (composition_file_name));
390
391         if (has_body) {
392                 body_file = fopen(body_file_name, "w");
393         }
394         composition_file = fopen(composition_file_name, "w");
395
396         if ((has_body && !body_file) || !composition_file) {
397                 clean_up_temporary_files();
398                 adios(EX_IOERR, NULL, "unable to open all of the temporary files.");
399         }
400
401         /* Copy non-attachment header fields to the temp composition file. */
402         rewind(draft_file);
403         while (get_line() != EOF && *field && *field != '-') {
404                 if (strncasecmp(field, attach_hdr, length) != 0 ||
405                                 field[length] != ':') {
406                         fprintf(composition_file, "%s\n", field);
407                 }
408         }
409         fputs("--------\n", composition_file);
410
411         if (has_body) {
412                 /* Copy the message body to the temporary file. */
413                 while ((c = getc(draft_file)) != EOF) {
414                         putc(c, body_file);
415                 }
416                 fclose(body_file);
417
418                 /* Add a mhbuild MIME composition file line for the body */
419                 /* charset will be discovered/guessed by mhbuild */
420                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
421         }
422
423         /*
424         ** Now, go back to the beginning of the draft file and look for
425         ** header fields that specify attachments.  Add a mhbuild MIME
426         ** composition file for each.
427         */
428         rewind(draft_file);
429         while (get_line() != EOF && *field && *field != '-') {
430                 if (strncasecmp(field, attach_hdr, length) == 0 &&
431                                 field[length] == ':') {
432                         p = trim(field+length+1);
433                         if (*p == '+') {
434                                 /* forwarded message */
435                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
436                         } else {
437                                 /* regular attachment */
438                                 make_mime_composition_file_entry(p);
439                         }
440                 }
441         }
442         fclose(composition_file);
443
444         /* We're ready to roll! */
445         if (execprogl("mhbuild", "mhbuild", composition_file_name,
446                         (char *)NULL) != 0) {
447                 /* some problem */
448                 clean_up_temporary_files();
449                 return (NOTOK);
450         }
451         /* Remove the automatically created backup of mhbuild. */
452         snprintf(buf, sizeof buf, "%s.orig", composition_file_name);
453         if (unlink(buf) == -1) {
454                 advise(NULL, "unable to remove original composition file.");
455         }
456
457         return (OK);
458 }
459
460 static int
461 signandenc(char *draft_file_name)
462 {
463         char buf[BUFSIZ];
464         int dosign = 0;
465         int doenc = 0;
466         int ret;
467
468         if (!(draft_file = fopen(draft_file_name, "r"))) {
469                 adios(EX_IOERR, NULL, "can't open draft file `%s'.", draft_file_name);
470         }
471
472         /* We'll grow the buffer as needed. */
473         field = (char *)mh_xmalloc(field_size = 256);
474
475         /* Scan the draft file for an attachment header field name. */
476         while (get_line() != EOF && *field != '\0' && *field != '-') {
477                 if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
478                                 field[strlen(sign_hdr)] == ':') {
479                         dosign = 1;
480                 }
481                 if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
482                                 field[strlen(enc_hdr)] == ':') {
483                         doenc = 1;
484                 }
485         }
486         if (!dosign && !doenc) {
487                 return DONE;
488         }
489
490         strcpy(composition_file_name, draft_file_name);
491
492         /* We're ready to roll! */
493         if (doenc) {
494                 ret = execprogl("mhsign", "mhsign", "-m", "-e",
495                                 draft_file_name, (char *)NULL);
496         } else {
497                 ret = execprogl("mhsign", "mhsign", "-m",
498                                 draft_file_name, (char *)NULL);
499         }
500         if (ret != 0) {
501                 /* some problem */
502                 return (NOTOK);
503         }
504         /* Remove the automatically created backup of mhsign. */
505         snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
506         if (unlink(buf) == -1) {
507                 advise(NULL, "unable to remove original draft file.");
508         }
509
510         return (OK);
511 }
512
513 static void
514 clean_up_temporary_files(void)
515 {
516         unlink(body_file_name);
517         unlink(composition_file_name);
518
519         return;
520 }
521
522 static int
523 get_line(void)
524 {
525         int c;  /* current character */
526         int n;  /* number of bytes in buffer */
527         char *p;
528
529         /*
530         ** Get a line from the input file, growing the field buffer as
531         ** needed.  We do this so that we can fit an entire line in the
532         ** buffer making it easy to do a string comparison on both the
533         ** field name and the field body which might be a long path name.
534         */
535         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
536                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
537                         ungetc(c, draft_file);
538                         c = '\n';
539                         break;
540                 }
541                 if (++n >= field_size - 1) {
542                         field = (char *)mh_xrealloc(field, field_size += 256);
543                         p = field + n - 1;
544                 }
545         }
546         *p = '\0';
547
548         return (c);
549 }
550
551 static void
552 make_mime_composition_file_entry(char *file_name)
553 {
554         FILE *fp;
555         struct node *np;
556         char *cp;
557         char content_type[BUFSIZ];
558         char cmdbuf[BUFSIZ];
559         char *cmd = mimetypequeryproc;
560         int semicolon = 0;
561
562         for (np = m_defs; np; np = np->n_next) {
563                 if (strcasecmp(np->n_name, mimetypequery)==0) {
564                         cmd = np->n_field;
565                         break;
566                 }
567         }
568         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
569
570         if (!(fp = popen(cmdbuf, "r"))) {
571                 clean_up_temporary_files();
572                 adios(EX_IOERR, NULL, "unable to determine content type with `%s'",
573                                 cmdbuf);
574         }
575         if (fgets(content_type, sizeof content_type, fp) &&
576                         (cp = strrchr(content_type, '\n'))) {
577                 *cp = '\0';
578         } else {
579                 strcpy(content_type, "application/octet-stream");
580                 admonish(NULL, "problems with `%s', using fall back type `%s'",
581                                 cmdbuf, content_type);
582         }
583         pclose(fp);
584
585         /* TODO: don't use access(2) because it checks for ruid, not euid */
586         if (access(file_name, R_OK) != 0) {
587                 clean_up_temporary_files();
588                 adios(EX_IOERR, NULL, "unable to access file `%s'", file_name);
589         }
590
591         /* Check for broken file(1). See man page mh-profile(5). */
592         for (cp=content_type; *cp; cp++) {
593                 if (isspace(*cp)) {
594                         if (!semicolon) {
595                                 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);
596                         }
597                 } else if (*cp == ';') {
598                         semicolon = 1;
599                 } else {
600                         semicolon = 0;
601                 }
602         }
603
604         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
605         fprintf(composition_file,
606                         "#%s; name=\"%s\" <> [%s] {attachment} %s\n",
607                         content_type, cp, cp, file_name);
608
609         return;
610 }
611
612 /*
613 ** The back-end of the message sending back-end.
614 ** Annotate original message, and call `spost' to send message.
615 */
616 static int
617 sendaux(char **vec, int vecp, char *drft, struct stat *st)
618 {
619         pid_t child_id;
620         int status;
621         char backup[BUFSIZ];
622
623         vec[vecp++] = drft;
624         if (distfile && distout(drft, distfile, backup) == NOTOK) {
625                 return DONE;
626         }
627         vec[vecp] = NULL;
628
629         switch (child_id = fork()) {
630         case -1:
631                 /* oops -- fork error */
632                 advise("fork", "unable to");
633                 return DONE;
634
635         case 0:
636                 /* child process -- send it */
637                 execvp(*vec, vec);
638                 fprintf(stderr, "unable to exec ");
639                 perror(*vec);
640                 _exit(EX_OSERR);
641                 break;  /* NOT REACHED */
642
643         default:
644                 /* parent process -- wait for it */
645                 status = pidwait(child_id, NOTOK);
646                 if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
647                         if (annotext) {
648                                 anno(st);
649                         }
650                 } else {
651                         /* spost failed */
652                         advise(NULL, "%s", strexit(status));
653                         if (distfile) {
654                                 unlink(drft);
655                                 if (rename(backup, drft) == NOTOK) {
656                                         advise(drft, "unable to rename %s to",
657                                                         backup);
658                                 }
659                         }
660                 }
661         }
662
663
664         return status ? NOTOK : status;
665 }
666
667
668 static void
669 anno(struct stat *st)
670 {
671         struct stat st2;
672         char *msgs, *folder;
673         char buf[BUFSIZ];
674         char *vec[MAXARGS];
675         int vecp = 0;
676         char *cp, *dp;
677
678         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
679                         st->st_mtime != st2.st_mtime ||
680                         st->st_dev != st2.st_dev ||
681                         st->st_ino != st2.st_ino)) {
682                 if (debugsw) {
683                         admonish(NULL, "$mhaltmsg mismatch");
684                 }
685                 return;
686         }
687
688         if (!(folder = getenv("mhfolder")) || !*folder) {
689                 if (debugsw) {
690                         admonish(NULL, "$mhfolder not set");
691                 }
692                 return;
693         }
694         if (!(msgs = getenv("mhmessages")) || !*msgs) {
695                 if (debugsw) {
696                         admonish(NULL, "$mhmessages not set");
697                 }
698                 return;
699         }
700         if (debugsw) {
701                 advise(NULL, "annotate as `%s': %s %s", annotext,
702                                 folder, msgs);
703         }
704         vec[vecp++] = "anno";
705         vec[vecp++] = "-comp";
706         vec[vecp++] = annotext;
707         snprintf(buf, sizeof buf, "+%s", folder);
708         vec[vecp++] = buf;
709
710         while (isspace(*msgs)) {
711                 msgs++;
712         }
713         for (cp=dp=msgs; *cp; cp++) {
714                 if (isspace(*cp)) {
715                         while (isspace(*cp)) {
716                                 *cp++ = '\0';
717                         }
718                         vec[vecp++] = dp;
719                         dp = cp;
720                 }
721         }
722         vec[vecp++] = dp;
723         vec[vecp] = NULL;
724         if (execprog(*vec, vec) != 0) {
725                 advise(NULL, "unable to annotate");
726         }
727 }
728
729
730 char*
731 strexit(int status)
732 {
733         if (WIFSIGNALED(status)) {
734                 return "spost or sendmail killed by signal";
735         }
736         if (!WIFEXITED(status)) {
737                 return "message not delivered to anyone";
738         }
739         switch (WEXITSTATUS(status)) {
740         case EX_TEMPFAIL:
741                 return "Temporary error, maybe the MTA has queued the message";
742         default:
743                 return "message not delivered to anyone";
744         }
745 }