Initialize vecp in send anno()
[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         switch (setjmp(env)) {
293         case OK:
294                 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
295                 if (status == OK) {
296                         /* move original draft to +trash folder */
297                         /* temporary close stdin, for refile not to ask */
298                         dupfd = dup(0);
299                         close(0);
300                         if (execprogl("refile", "refile", "-file",
301                                         original_draft, "+trash",
302                                         (char *)NULL) != 0) {
303                                 advise(NULL, "unable to trash the draft");
304                         }
305                         dup2(dupfd, 0);
306                         close(dupfd);
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                 } else {
657                         /* spost failed */
658                         advise(NULL, "%s", strexit(status));
659                         if (distfile) {
660                                 unlink(drft);
661                                 if (rename(backup, drft) == NOTOK) {
662                                         advise(drft, "unable to rename %s to",
663                                                         backup);
664                                 }
665                         }
666                 }
667         }
668
669
670         return status;
671 }
672
673
674 static void
675 anno(struct stat *st)
676 {
677         struct stat st2;
678         char *msgs, *folder;
679         char buf[BUFSIZ];
680         char *vec[MAXARGS];
681         int vecp = 0;
682         char *cp, *dp;
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         vec[vecp++] = "anno";
711         vec[vecp++] = "-comp";
712         vec[vecp++] = annotext;
713         snprintf(buf, sizeof buf, "+%s", folder);
714         vec[vecp++] = buf;
715
716         while (isspace(*msgs)) {
717                 msgs++;
718         }
719         for (cp=dp=msgs; *cp; cp++) {
720                 if (isspace(*cp)) {
721                         while (isspace(*cp)) {
722                                 *cp++ = '\0';
723                         }
724                         vec[vecp++] = dp;
725                         dp = cp;
726                 }
727         }
728         vec[vecp++] = dp;
729         vec[vecp] = NULL;
730         if (execprog(*vec, vec) != 0) {
731                 advise(NULL, "unable to annotate");
732         }
733 }
734
735
736 char*
737 strexit(int status)
738 {
739         if (WIFSIGNALED(status)) {
740                 return "spost or sendmail killed by signal";
741         }
742         if (!WIFEXITED(status)) {
743                 return "message not delivered to anyone";
744         }
745         switch (WEXITSTATUS(status)) {
746         case EX_TEMPFAIL:
747                 return "Temporary error, maybe the MTA has queued the message";
748         default:
749                 return "message not delivered to anyone";
750         }
751 }
752
753
754 static void
755 armed_done(int status)
756 {
757         longjmp(env, status ? status : NOTOK);
758
759         exit(status);
760 }