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