adb2039f04bac66c6fd1e71204451c684de3e2cb
[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         sprintf(buf, "mhbuild %s", composition_file_name);
452         if (system(buf) != 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
473         if (!(draft_file = fopen(draft_file_name, "r"))) {
474                 adios(NULL, "can't open draft file `%s'.", draft_file_name);
475         }
476
477         /* We'll grow the buffer as needed. */
478         field = (char *)mh_xmalloc(field_size = 256);
479
480         /* Scan the draft file for an attachment header field name. */
481         while (get_line() != EOF && *field != '\0' && *field != '-') {
482                 if (strncasecmp(field, sign_hdr, strlen(sign_hdr))==0 &&
483                                 field[strlen(sign_hdr)] == ':') {
484                         dosign = 1;
485                 }
486                 if (strncasecmp(field, enc_hdr, strlen(enc_hdr))==0 &&
487                                 field[strlen(enc_hdr)] == ':') {
488                         doenc = 1;
489                 }
490         }
491         if (!dosign && !doenc) {
492                 return DONE;
493         }
494
495         strcpy(composition_file_name, draft_file_name);
496
497         /* We're ready to roll! */
498         sprintf(buf, "mhsign -m%s '%s'", doenc ? " -e" : "",
499                         draft_file_name);
500         if (system(buf) != 0) {
501                 /* some problem */
502                 return (NOTOK);
503         }
504         /* Remove the automatically created backup of mhsign. */
505         snprintf(buf, sizeof buf, "%s.orig", draft_file_name);
506         if (unlink(buf) == -1) {
507                 advise(NULL, "unable to remove original draft file.");
508         }
509
510         return (OK);
511 }
512
513 static void
514 clean_up_temporary_files(void)
515 {
516         unlink(body_file_name);
517         unlink(composition_file_name);
518
519         return;
520 }
521
522 static int
523 get_line(void)
524 {
525         int c;  /* current character */
526         int n;  /* number of bytes in buffer */
527         char *p;
528
529         /*
530         ** Get a line from the input file, growing the field buffer as
531         ** needed.  We do this so that we can fit an entire line in the
532         ** buffer making it easy to do a string comparison on both the
533         ** field name and the field body which might be a long path name.
534         */
535         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
536                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
537                         ungetc(c, draft_file);
538                         c = '\n';
539                         break;
540                 }
541                 if (++n >= field_size - 1) {
542                         field = (char *)mh_xrealloc(field, field_size += 256);
543                         p = field + n - 1;
544                 }
545         }
546         *p = '\0';
547
548         return (c);
549 }
550
551 static void
552 make_mime_composition_file_entry(char *file_name)
553 {
554         FILE *fp;
555         struct node *np;
556         char *cp;
557         char content_type[BUFSIZ];
558         char cmdbuf[BUFSIZ];
559         char *cmd = mimetypequeryproc;
560         int semicolon = 0;
561
562         for (np = m_defs; np; np = np->n_next) {
563                 if (strcasecmp(np->n_name, mimetypequery)==0) {
564                         cmd = np->n_field;
565                         break;
566                 }
567         }
568         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
569
570         if (!(fp = popen(cmdbuf, "r"))) {
571                 clean_up_temporary_files();
572                 adios(NULL, "unable to determine content type with `%s'",
573                                 cmdbuf);
574         }
575         if (fgets(content_type, sizeof content_type, fp) &&
576                         (cp = strrchr(content_type, '\n'))) {
577                 *cp = '\0';
578         } else {
579                 strcpy(content_type, "application/octet-stream");
580                 admonish(NULL, "problems with `%s', using fall back type `%s'",
581                                 cmdbuf, content_type);
582         }
583         pclose(fp);
584
585         /* TODO: don't use access(2) because it checks for ruid, not euid */
586         if (access(file_name, R_OK) != 0) {
587                 clean_up_temporary_files();
588                 adios(NULL, "unable to access file `%s'", file_name);
589         }
590
591         /* Check for broken file(1). See man page mh-profile(5). */
592         for (cp=content_type; *cp; cp++) {
593                 if (isspace(*cp)) {
594                         if (!semicolon) {
595                                 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);
596                         }
597                 } else if (*cp == ';') {
598                         semicolon = 1;
599                 } else {
600                         semicolon = 0;
601                 }
602         }
603
604         cp = (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1;
605         fprintf(composition_file,
606                         "#%s; name=\"%s\" <> [%s] {attachment} %s\n",
607                         content_type, cp, cp, file_name);
608
609         return;
610 }
611
612 /*
613 ** The back-end of the message sending back-end.
614 ** Annotate original message, and call `spost' to send message.
615 */
616 static int
617 sendaux(char **vec, int vecp, char *drft, struct stat *st)
618 {
619         pid_t child_id;
620         int status;
621         char backup[BUFSIZ];
622
623         vec[vecp++] = drft;
624         if (distfile && distout(drft, distfile, backup) == NOTOK) {
625                 done(1);
626         }
627         vec[vecp] = NULL;
628
629         switch (child_id = fork()) {
630         case -1:
631                 /* oops -- fork error */
632                 adios("fork", "unable to");
633                 break;  /* NOT REACHED */
634
635         case 0:
636                 /* child process -- send it */
637                 execvp(*vec, vec);
638                 fprintf(stderr, "unable to exec ");
639                 perror(*vec);
640                 _exit(-1);
641                 break;  /* NOT REACHED */
642
643         default:
644                 /* parent process -- wait for it */
645                 status = pidwait(child_id, NOTOK);
646                 if (WIFEXITED(status) && WEXITSTATUS(status) == EX_OK) {
647                         if (annotext) {
648                                 anno(st);
649                         }
650                 }
651                 else {
652                         advise(NULL, "%s", strexit(status));
653                         if (verbosesw <= 0) {
654                                 advise(NULL, "Try using -v to get better output");
655                         }
656                         if (distfile) {
657                                 unlink(drft);
658                                 if (rename(backup, drft) == NOTOK) {
659                                         advise(drft, "unable to rename %s to",
660                                                         backup);
661                                 }
662                         }
663                 }
664         }
665
666
667         return status;
668 }
669
670
671 static void
672 anno(struct stat *st)
673 {
674         struct stat st2;
675         char *msgs, *folder;
676         char buf[BUFSIZ];
677
678         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
679                         st->st_mtime != st2.st_mtime ||
680                         st->st_dev != st2.st_dev ||
681                         st->st_ino != st2.st_ino)) {
682                 if (debugsw) {
683                         admonish(NULL, "$mhaltmsg mismatch");
684                 }
685                 return;
686         }
687
688         if (!(folder = getenv("mhfolder")) || !*folder) {
689                 if (debugsw) {
690                         admonish(NULL, "$mhfolder not set");
691                 }
692                 return;
693         }
694         if (!(msgs = getenv("mhmessages")) || !*msgs) {
695                 if (debugsw) {
696                         admonish(NULL, "$mhmessages not set");
697                 }
698                 return;
699         }
700         if (debugsw) {
701                 advise(NULL, "annotate as `%s': %s %s", annotext,
702                                 folder, msgs);
703         }
704         snprintf(buf, sizeof buf, "anno -comp '%s' '+%s' %s",
705                         annotext, folder, msgs);
706         if (system(buf) != 0) {
707                 advise(NULL, "unable to annotate");
708         }
709 }
710
711
712 char*
713 strexit(int status)
714 {
715         if (WIFSIGNALED(status)) {
716                 return "spost or sendmail killed by signal";
717         }
718         if (!WIFEXITED(status)) {
719                 return "sendmail stopt for unknown reasen, message not deliverd to anyone";
720         }
721         switch (WEXITSTATUS(status)) {
722                 case EX_TEMPFAIL:
723                         return "Temporary error, maby the MTA hase queued the Mail";
724                 default:
725                         return "sendmail stopt for unknown reasen, message not deliverd to anyone";
726         }
727 }
728
729
730 static void
731 armed_done(int status)
732 {
733         longjmp(env, status ? status : NOTOK);
734
735         exit(status);
736 }