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