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