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