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