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