f8b415cb12dd692a7ee577934202bf8a9106f69d
[mmh] / uip / sendsbr.c
1 /*
2 ** sendsbr.c -- routines to help WhatNow/Send along
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 <h/signals.h>
11 #include <setjmp.h>
12 #include <signal.h>
13 #include <fcntl.h>
14 #include <h/mime.h>
15 #include <h/tws.h>
16 #include <h/utils.h>
17
18 #ifdef TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # ifdef TM_IN_SYS_TIME
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 int debugsw = 0;  /* global */
30 int forwsw  = 1;
31 int inplace = 1;
32 int pushsw  = 0;
33 int verbsw  = 0;
34
35 char *altmsg   = NULL;  /*  .. */
36 char *annotext = NULL;
37 char *distfile = NULL;
38
39 static jmp_buf env;
40
41 /* name of temp file for body content */
42 static char body_file_name[MAXPATHLEN + 1];
43 /* name of mhbuild composition temporary file */
44 static char composition_file_name[MAXPATHLEN + 1]; 
45 static int field_size;  /* size of header field buffer */
46 static char *field;  /* header field buffer */
47 static FILE *draft_file;  /* draft file pointer */
48 static FILE *body_file;  /* body file pointer */
49 static FILE *composition_file;  /* composition file pointer */
50
51 /*
52 ** external prototypes
53 */
54 int sendsbr(char **, int, char *, struct stat *, int);
55 char *getusername(void);
56
57 /*
58 ** static prototypes
59 */
60 static void armed_done(int) NORETURN;
61 static void alert(char *, int);
62 static int tmp_fd(void);
63 static void anno(int, struct stat *);
64 static void annoaux(int);
65 static int sendaux(char **, int, char *, struct stat *);
66
67 static int attach(char *);
68 static void clean_up_temporary_files(void);
69 static int get_line(void);
70 static void make_mime_composition_file_entry(char *);
71
72
73 /*
74 ** Entry point into (back-end) routines to send message.
75 */
76
77 int
78 sendsbr(char **vec, int vecp, char *drft, struct stat *st, int rename_drft)
79 {
80         int status;
81         char buffer[BUFSIZ];
82         char *original_draft;  /* name of original draft file */
83         char *p;  /* string pointer for building file name */
84
85         /*
86         ** Save the original name of the draft file.  The name of the
87         ** draft file is changed to a temporary file containing the built
88         ** MIME message if there are attachments.  We need the original
89         ** name so that it can be renamed after the message is sent.
90         */
91
92         original_draft = drft;
93
94         /*
95         ** Convert the draft to a MIME message.
96         ** Use the mhbuild composition file for the draft if there was
97         ** a successful conversion because that now contains the MIME
98         ** message.  A nice side effect of this is that it leaves the
99         ** original draft file untouched so that it can be retrieved
100         ** and modified if desired.
101         */
102         switch (attach(drft)) {
103         case OK:
104                 drft = composition_file_name;
105                 break;
106
107         case NOTOK:
108                 return (NOTOK);
109
110         case DONE:
111                 break;
112         }
113
114         done=armed_done;
115         switch (setjmp(env)) {
116         case OK:
117                 status = sendaux(vec, vecp, drft, st) ? NOTOK : OK;
118                 /* rename the original draft */
119                 if (rename_drft && status == OK &&
120                                 rename(original_draft, strncpy(buffer,
121                                 m_backup(original_draft), sizeof(buffer)))
122                                 == NOTOK)
123                         advise(buffer, "unable to rename %s to", drft);
124                 break;
125
126         default:
127                 status = DONE;
128                 break;
129         }
130
131         done=exit;
132         if (distfile)
133                 unlink(distfile);
134
135         /*
136         ** Get rid of any temporary files that we created for attachments.
137         ** Also get rid of the renamed composition file that mhbuild
138         ** leaves as a turd.  It looks confusing, but we use the body
139         ** file name to help build the renamed composition file name.
140         */
141
142         if (drft == composition_file_name) {
143                 clean_up_temporary_files();
144
145                 if (strlen(composition_file_name) >=
146                                 sizeof (composition_file_name) - 6)
147                         advise(NULL, "unable to remove original composition file.");
148
149                 else {
150                         if ((p = strrchr(composition_file_name, '/')) == NULL)
151                                 p = composition_file_name;
152                         else
153                                 p++;
154
155                         strcpy(body_file_name, p);
156                         *p++ = ',';
157                         strcpy(p, body_file_name);
158                         strcat(p, ".orig");
159
160                         unlink(composition_file_name);
161                 }
162         }
163
164         return status;
165 }
166
167 static int
168 attach(char *draft_file_name)
169 {
170         char buf[MAXPATHLEN + 6];  /* miscellaneous buffer */
171         int c;  /* current character for body copy */
172         int has_attachment;  /* draft has at least one attachment */
173         int has_body;  /* draft has a message body */
174         int non_ascii; /* msg body contains non-ASCII chars */
175         int length;  /* length of attachment header field name */
176         char *p;  /* miscellaneous string pointer */
177
178         /* Open up the draft file. */
179         if ((draft_file = fopen(draft_file_name, "r")) == (FILE *)0)
180                 adios(NULL, "can't open draft file `%s'.",
181                                 draft_file_name);
182
183         /*
184         **  Allocate a buffer to hold the header components as they're read in.
185         **  This buffer might need to be quite large, so we grow it as needed.
186         */
187         field = (char *)mh_xmalloc(field_size = 256);
188
189         /*
190         ** Scan the draft file for an attachment header field name.
191         ** The existence of one indicates that the
192         ** draft has attachments.  Bail out if there are no attachments
193         ** because we're done.  Read to the end of the headers even if
194         ** we have no attachments.
195         */
196         length = strlen(attach_hdr);
197
198         has_attachment = 0;
199
200         while (get_line() != EOF && *field != '\0' && *field != '-') {
201                 if (strncasecmp(field, attach_hdr, length) == 0 &&
202                                 field[length] == ':') {
203                         has_attachment = 1;
204                 }
205         }
206
207         /*
208         ** Look for at least one non-blank line in the body of the
209         ** message which indicates content in the body.
210         ** Check if body contains at least one non-blank (= not empty)
211         ** and if it contains any non-ASCII chars (= need MIME).
212         */
213         has_body = 0;
214         non_ascii = 0;
215
216         while (get_line() != EOF) {
217                 for (p = field; *p != '\0'; p++) {
218                         if (*p != ' ' && *p != '\t') {
219                                 has_body = 1;
220                         }
221                         if (*p > 127 || *p < 0) {
222                                 non_ascii = 1;
223                         }
224                 }
225                 if (has_body && non_ascii)
226                         break;
227         }
228
229         /*
230         ** Bail out if there are no attachments and only ASCII text.
231         ** This means we don't need to convert it to MIME.
232         */
233         if (!has_attachment && non_ascii==0) {
234                 return DONE;
235         }
236
237         /*
238         ** Else: mimify
239         */
240
241         /* Make names for the temporary files.  */
242         strncpy(body_file_name,
243                         m_mktemp(toabsdir(invo_name), NULL, NULL),
244                         sizeof (body_file_name));
245         strncpy(composition_file_name,
246                         m_mktemp(toabsdir(invo_name), NULL, NULL),
247                         sizeof (composition_file_name));
248
249         if (has_body)
250                 body_file = fopen(body_file_name, "w");
251
252         composition_file = fopen(composition_file_name, "w");
253
254         if ((has_body && !body_file) || !composition_file) {
255                 clean_up_temporary_files();
256                 adios(NULL, "unable to open all of the temporary files.");
257         }
258
259         /*
260         ** Start at the beginning of the draft file.  Copy all
261         ** non-attachment header fields to the temporary composition file.
262         ** Then add the dashed line separator.
263         */
264         rewind(draft_file);
265         while (get_line() != EOF && *field && *field != '-') {
266                 if (strncasecmp(field, attach_hdr, length) != 0 ||
267                                 field[length] != ':') {
268                         fprintf(composition_file, "%s\n", field);
269                 }
270         }
271         fputs("--------\n", composition_file);
272
273         if (has_body) {
274                 /* Copy the message body to the temporary file. */
275                 while ((c = getc(draft_file)) != EOF) {
276                         putc(c, body_file);
277                 }
278                 fclose(body_file);
279
280                 /* Add a mhbuild MIME composition file line for the body */
281                 /* charset will be discovered/guessed by buildmimeproc */
282                 fprintf(composition_file, "#text/plain %s\n", body_file_name);
283         }
284
285         /*
286         ** Now, go back to the beginning of the draft file and look for
287         ** header fields that specify attachments.  Add a mhbuild MIME
288         ** composition file for each.
289         */
290         rewind(draft_file);
291         while (get_line() != EOF && *field && *field != '-') {
292                 if (strncasecmp(field, attach_hdr, length) == 0 &&
293                                 field[length] == ':') {
294                         for (p = field+length+1; *p==' ' || *p=='\t'; p++) {
295                                 continue;
296                         }
297                         if (*p == '+') {
298                                 /* forwarded message */
299                                 fprintf(composition_file, "#forw [forwarded message(s)] %s\n", p);
300                         } else {
301                                 make_mime_composition_file_entry(p);
302                         }
303                 }
304         }
305
306         fclose(composition_file);
307
308         /*
309         ** We're ready to roll!  Run mhbuild on the composition file.
310         ** Note that mhbuild is in the context as buildmimeproc.
311         */
312         sprintf(buf, "%s %s", buildmimeproc, composition_file_name);
313
314         if (system(buf) != 0) {
315                 clean_up_temporary_files();
316                 return (NOTOK);
317         }
318
319         return (OK);
320 }
321
322 static void
323 clean_up_temporary_files(void)
324 {
325         unlink(body_file_name);
326         unlink(composition_file_name);
327
328         return;
329 }
330
331 static int
332 get_line(void)
333 {
334         int c;  /* current character */
335         int n;  /* number of bytes in buffer */
336         char *p;  /* buffer pointer */
337
338         /*
339         ** Get a line from the input file, growing the field buffer as
340         ** needed.  We do this so that we can fit an entire line in the
341         ** buffer making it easy to do a string comparison on both the
342         ** field name and the field body which might be a long path name.
343         */
344
345         for (n = 0, p = field; (c = getc(draft_file)) != EOF; *p++ = c) {
346                 if (c == '\n' && (c = getc(draft_file)) != ' ' && c != '\t') {
347                         ungetc(c, draft_file);
348                         c = '\n';
349                         break;
350                 }
351
352                 if (++n >= field_size - 1) {
353                         field = (char *)mh_xrealloc((void *)field, field_size += 256);
354
355                         p = field + n - 1;
356                 }
357         }
358
359         /* NUL-terminate the field. */
360         *p = '\0';
361
362         return (c);
363 }
364
365 static void
366 make_mime_composition_file_entry(char *file_name)
367 {
368         FILE *fp;
369         struct node *np;
370         char *cp;
371         char content_type[BUFSIZ];
372         char cmdbuf[BUFSIZ];
373         char *cmd = mimetypequeryproc;
374
375         for (np = m_defs; np; np = np->n_next) {
376                 if (strcasecmp(np->n_name, mimetypequery)==0) {
377                         cmd = np->n_field;
378                         break;
379                 }
380         }
381         snprintf(cmdbuf, sizeof cmdbuf, "%s %s", cmd, file_name);
382
383         if (!(fp = popen(cmdbuf, "r"))) {
384                 clean_up_temporary_files();
385                 adios(NULL, "unable to determine content type with `%s'",
386                                 cmdbuf);
387         }
388         if (fgets(content_type, sizeof content_type, fp) &&
389                         (cp = strrchr(content_type, '\n'))) {
390                 *cp = '\0';
391         } else {
392                 strcpy(content_type, "application/octet-stream");
393                 admonish(NULL, "problems with `%s', using fall back type `%s'",
394                                 cmdbuf, content_type);
395         }
396         pclose(fp);
397
398         /* TODO: don't use access(2) because it checks for ruid, not euid */
399         if (access(file_name, R_OK) != 0) {
400                 clean_up_temporary_files();
401                 adios(NULL, "unable to access file `%s'", file_name);
402         }
403
404         fprintf(composition_file, "#%s; name=\"%s\" <>{attachment}",
405                 content_type,
406                 (!(cp = strrchr(file_name, '/'))) ? file_name : cp + 1);
407
408         fprintf(composition_file, " %s\n", file_name);
409
410         return;
411 }
412
413 /*
414 ** Annotate original message, and
415 ** call `postproc' to send message.
416 */
417
418 static int
419 sendaux(char **vec, int vecp, char *drft, struct stat *st)
420 {
421         pid_t child_id;
422         int i, status, fd, fd2;
423         char backup[BUFSIZ];
424
425         fd = pushsw ? tmp_fd() : NOTOK;
426         fd2 = NOTOK;
427
428         vec[vecp++] = drft;
429         if (annotext && (fd2 = tmp_fd()) == NOTOK) {
430                 admonish(NULL, "unable to create file for annotation list");
431         }
432         if (distfile && distout(drft, distfile, backup) == NOTOK)
433                 done(1);
434         vec[vecp] = NULL;
435
436         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
437                 sleep(5);
438
439         switch (child_id) {
440         case -1:
441                 /* oops -- fork error */
442                 adios("fork", "unable to");
443                 break;  /* NOT REACHED */
444
445         case 0:
446                 /*
447                 ** child process -- send it
448                 **
449                 ** If fd is ok, then we are pushing and fd points to temp
450                 ** file, so capture anything on stdout and stderr there.
451                 */
452                 if (fd != NOTOK) {
453                         dup2(fd, fileno(stdout));
454                         dup2(fd, fileno(stderr));
455                         close(fd);
456                 }
457                 execvp(postproc, vec);
458                 fprintf(stderr, "unable to exec ");
459                 perror(postproc);
460                 _exit(-1);
461                 break;  /* NOT REACHED */
462
463         default:
464                 /*
465                 ** parent process -- wait for it
466                 */
467                 if ((status = pidwait(child_id, NOTOK)) == OK) {
468                         if (annotext && fd2 != NOTOK)
469                                 anno(fd2, st);
470                 } else {
471                         /*
472                         ** If postproc failed, and we have good fd (which
473                         ** means we pushed), then mail error message
474                         ** (and possibly the draft) back to the user.
475                         */
476                         if (fd != NOTOK) {
477                                 alert(drft, fd);
478                                 close(fd);
479                         } else {
480                                 advise(NULL, "message not delivered to anyone");
481                         }
482                         if (annotext && fd2 != NOTOK)
483                                 close(fd2);
484                         if (distfile) {
485                                 unlink(drft);
486                                 if (rename(backup, drft) == NOTOK)
487                                         advise(drft, "unable to rename %s to",
488                                                         backup);
489                         }
490                 }
491                 break;
492         }
493
494         return status;
495 }
496
497
498 /*
499 ** Mail error notification (and possibly a copy of the
500 ** message) back to the user, using the mailproc
501 */
502
503 static void
504 alert(char *file, int out)
505 {
506         pid_t child_id;
507         int i, in;
508         char buf[BUFSIZ];
509
510         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
511                 sleep(5);
512
513         switch (child_id) {
514         case NOTOK:
515                 /* oops -- fork error */
516                 advise("fork", "unable to");
517
518         case OK:
519                 /* child process -- send it */
520                 SIGNAL(SIGHUP, SIG_IGN);
521                 SIGNAL(SIGINT, SIG_IGN);
522                 SIGNAL(SIGQUIT, SIG_IGN);
523                 SIGNAL(SIGTERM, SIG_IGN);
524                 if (forwsw) {
525                         if ((in = open(file, O_RDONLY)) == NOTOK) {
526                                 admonish(file, "unable to re-open");
527                         } else {
528                                 lseek(out, (off_t) 0, SEEK_END);
529                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
530                                 write(out, buf, strlen(buf));
531                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
532                                 write(out, buf, strlen(buf));
533                                 cpydgst(in, out, file, "temporary file");
534                                 close(in);
535                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
536                                 write(out, buf, strlen(buf));
537                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
538                                         admonish(buf, "unable to rename %s to", file);
539                         }
540                 }
541                 lseek(out, (off_t) 0, SEEK_SET);
542                 dup2(out, fileno(stdin));
543                 close(out);
544                 /* create subject for error notification */
545                 snprintf(buf, sizeof(buf), "send failed on %s",
546                                 forwsw ? "enclosed draft" : file);
547
548                 execlp(mailproc, mhbasename(mailproc), getusername(),
549                                 "-subject", buf, NULL);
550                 fprintf(stderr, "unable to exec ");
551                 perror(mailproc);
552                 _exit(-1);
553
554         default:  /* no waiting... */
555                 break;
556         }
557 }
558
559
560 static int
561 tmp_fd(void)
562 {
563         int fd;
564         char *tfile = NULL;
565
566         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
567         if (tfile == NULL) return NOTOK;
568         fchmod(fd, 0600);
569
570         if (debugsw)
571                 advise(NULL, "temporary file %s selected", tfile);
572         else
573                 if (unlink(tfile) == NOTOK)
574                         advise(tfile, "unable to remove");
575
576         return fd;
577 }
578
579
580 static void
581 anno(int fd, struct stat *st)
582 {
583         pid_t child_id;
584         sigset_t set, oset;
585         static char *cwd = NULL;
586         struct stat st2;
587
588         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
589                         st->st_mtime != st2.st_mtime ||
590                         st->st_dev != st2.st_dev ||
591                         st->st_ino != st2.st_ino)) {
592                 if (debugsw)
593                         admonish(NULL, "$mhaltmsg mismatch");
594                 return;
595         }
596
597         child_id = debugsw ? NOTOK : fork();
598         switch (child_id) {
599         case NOTOK:  /* oops */
600                 if (!debugsw)
601                         advise(NULL, "unable to fork, so doing annotations by hand...");
602                 if (cwd == NULL)
603                         cwd = getcpy(pwd());
604
605         case OK:
606                 /* block a few signals */
607                 sigemptyset(&set);
608                 sigaddset(&set, SIGHUP);
609                 sigaddset(&set, SIGINT);
610                 sigaddset(&set, SIGQUIT);
611                 sigaddset(&set, SIGTERM);
612                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
613
614                 annoaux(fd);
615                 if (child_id == OK)
616                         _exit(0);
617
618                 /* reset the signal mask */
619                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
620
621                 chdir(cwd);
622                 break;
623
624         default:  /* no waiting... */
625                 close(fd);
626                 break;
627         }
628 }
629
630
631 static void
632 annoaux(int fd)
633 {
634         int fd2, fd3, msgnum;
635         char *cp, *folder, *maildir;
636         char buffer[BUFSIZ], **ap;
637         FILE *fp;
638         struct msgs *mp;
639
640         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
641                 if (debugsw)
642                         admonish(NULL, "$mhfolder not set");
643                 return;
644         }
645         maildir = toabsdir(folder);
646         if (chdir(maildir) == NOTOK) {
647                 if (debugsw)
648                         admonish(maildir, "unable to change directory to");
649                 return;
650         }
651         if (!(mp = folder_read(folder))) {
652                 if (debugsw)
653                         admonish(NULL, "unable to read folder %s", folder);
654                 return;
655         }
656
657         /* check for empty folder */
658         if (mp->nummsg == 0) {
659                 if (debugsw)
660                         admonish(NULL, "no messages in %s", folder);
661                 goto oops;
662         }
663
664         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
665                 if (debugsw)
666                         admonish(NULL, "$mhmessages not set");
667                 goto oops;
668         }
669         if (!debugsw  /* MOBY HACK... */
670                         && pushsw
671                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
672                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
673                 dup2(fd3, fileno(stderr));
674                 close(fd3);
675         }
676         else
677                 fd2 = NOTOK;
678         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
679                 m_convert(mp, *ap);
680         free(cp);
681         if (fd2 != NOTOK)
682                 dup2(fd2, fileno(stderr));
683         if (mp->numsel == 0) {
684                 if (debugsw)
685                         admonish(NULL, "no messages to annotate");
686                 goto oops;
687         }
688
689         lseek(fd, (off_t) 0, SEEK_SET);
690         if ((fp = fdopen(fd, "r")) == NULL) {
691                 if (debugsw)
692                         admonish(NULL, "unable to fdopen annotation list");
693                 goto oops;
694         }
695         cp = NULL;
696         while (fgets(buffer, sizeof(buffer), fp) != NULL)
697                 cp = add(buffer, cp);
698         fclose(fp);
699
700         if (debugsw)
701                 advise(NULL, "annotate%s with %s: \"%s\"",
702                                 inplace ? " inplace" : "", annotext, cp);
703         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
704                 if (is_selected(mp, msgnum)) {
705                         if (debugsw)
706                                 advise(NULL, "annotate message %d", msgnum);
707                         annotate(m_name(msgnum), annotext, cp, inplace,
708                                         1, -2, 0);
709                 }
710         }
711
712         free(cp);
713
714 oops:
715         folder_free(mp);  /* free folder/message structure */
716 }
717
718
719 static void
720 armed_done(int status)
721 {
722         longjmp(env, status ? status : NOTOK);
723
724         exit(status);
725 }