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