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