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