Updated .gitignore and removed the unused mts.conf.in.
[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 static int
418 sendaux(char **vec, int vecp, char *drft, struct stat *st)
419 {
420         pid_t child_id;
421         int i, status, fd, fd2;
422         char backup[BUFSIZ];
423
424         fd = pushsw ? tmp_fd() : NOTOK;
425         fd2 = NOTOK;
426
427         vec[vecp++] = drft;
428         if (annotext && (fd2 = tmp_fd()) == NOTOK) {
429                 admonish(NULL, "unable to create file for annotation list");
430         }
431         if (distfile && distout(drft, distfile, backup) == NOTOK)
432                 done(1);
433         vec[vecp] = NULL;
434
435         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
436                 sleep(5);
437
438         switch (child_id) {
439         case -1:
440                 /* oops -- fork error */
441                 adios("fork", "unable to");
442                 break;  /* NOT REACHED */
443
444         case 0:
445                 /*
446                 ** child process -- send it
447                 **
448                 ** If fd is ok, then we are pushing and fd points to temp
449                 ** file, so capture anything on stdout and stderr there.
450                 */
451                 if (fd != NOTOK) {
452                         dup2(fd, fileno(stdout));
453                         dup2(fd, fileno(stderr));
454                         close(fd);
455                 }
456                 execvp(postproc, vec);
457                 fprintf(stderr, "unable to exec ");
458                 perror(postproc);
459                 _exit(-1);
460                 break;  /* NOT REACHED */
461
462         default:
463                 /*
464                 ** parent process -- wait for it
465                 */
466                 if ((status = pidwait(child_id, NOTOK)) == OK) {
467                         if (annotext && fd2 != NOTOK)
468                                 anno(fd2, st);
469                 } else {
470                         /*
471                         ** If postproc failed, and we have good fd (which
472                         ** means we pushed), then mail error message
473                         ** (and possibly the draft) back to the user.
474                         */
475                         if (fd != NOTOK) {
476                                 alert(drft, fd);
477                                 close(fd);
478                         } else {
479                                 advise(NULL, "message not delivered to anyone");
480                         }
481                         if (annotext && fd2 != NOTOK)
482                                 close(fd2);
483                         if (distfile) {
484                                 unlink(drft);
485                                 if (rename(backup, drft) == NOTOK)
486                                         advise(drft, "unable to rename %s to",
487                                                         backup);
488                         }
489                 }
490                 break;
491         }
492
493         return status;
494 }
495
496
497 /*
498 ** Mail error notification (and possibly a copy of the
499 ** message) back to the user, using the mailproc
500 */
501 static void
502 alert(char *file, int out)
503 {
504         pid_t child_id;
505         int i, in;
506         char buf[BUFSIZ];
507
508         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
509                 sleep(5);
510
511         switch (child_id) {
512         case NOTOK:
513                 /* oops -- fork error */
514                 advise("fork", "unable to");
515
516         case OK:
517                 /* child process -- send it */
518                 SIGNAL(SIGHUP, SIG_IGN);
519                 SIGNAL(SIGINT, SIG_IGN);
520                 SIGNAL(SIGQUIT, SIG_IGN);
521                 SIGNAL(SIGTERM, SIG_IGN);
522                 if (forwsw) {
523                         if ((in = open(file, O_RDONLY)) == NOTOK) {
524                                 admonish(file, "unable to re-open");
525                         } else {
526                                 lseek(out, (off_t) 0, SEEK_END);
527                                 strncpy(buf, "\nMessage not delivered to anyone.\n", sizeof(buf));
528                                 write(out, buf, strlen(buf));
529                                 strncpy(buf, "\n------- Unsent Draft\n\n", sizeof(buf));
530                                 write(out, buf, strlen(buf));
531                                 cpydgst(in, out, file, "temporary file");
532                                 close(in);
533                                 strncpy(buf, "\n------- End of Unsent Draft\n", sizeof(buf));
534                                 write(out, buf, strlen(buf));
535                                 if (rename(file, strncpy(buf, m_backup(file), sizeof(buf))) == NOTOK)
536                                         admonish(buf, "unable to rename %s to", file);
537                         }
538                 }
539                 lseek(out, (off_t) 0, SEEK_SET);
540                 dup2(out, fileno(stdin));
541                 close(out);
542                 /* create subject for error notification */
543                 snprintf(buf, sizeof(buf), "send failed on %s",
544                                 forwsw ? "enclosed draft" : file);
545
546                 execlp(mailproc, mhbasename(mailproc), getusername(),
547                                 "-subject", buf, NULL);
548                 fprintf(stderr, "unable to exec ");
549                 perror(mailproc);
550                 _exit(-1);
551
552         default:  /* no waiting... */
553                 break;
554         }
555 }
556
557
558 static int
559 tmp_fd(void)
560 {
561         int fd;
562         char *tfile = NULL;
563
564         tfile = m_mktemp2(NULL, invo_name, &fd, NULL);
565         if (tfile == NULL) return NOTOK;
566         fchmod(fd, 0600);
567
568         if (debugsw)
569                 advise(NULL, "temporary file %s selected", tfile);
570         else
571                 if (unlink(tfile) == NOTOK)
572                         advise(tfile, "unable to remove");
573
574         return fd;
575 }
576
577
578 static void
579 anno(int fd, struct stat *st)
580 {
581         pid_t child_id;
582         sigset_t set, oset;
583         static char *cwd = NULL;
584         struct stat st2;
585
586         if (altmsg && (stat(altmsg, &st2) == NOTOK ||
587                         st->st_mtime != st2.st_mtime ||
588                         st->st_dev != st2.st_dev ||
589                         st->st_ino != st2.st_ino)) {
590                 if (debugsw)
591                         admonish(NULL, "$mhaltmsg mismatch");
592                 return;
593         }
594
595         child_id = debugsw ? NOTOK : fork();
596         switch (child_id) {
597         case NOTOK:  /* oops */
598                 if (!debugsw)
599                         advise(NULL, "unable to fork, so doing annotations by hand...");
600                 if (cwd == NULL)
601                         cwd = getcpy(pwd());
602                 /* fall */
603
604         case OK:
605                 /* block a few signals */
606                 sigemptyset(&set);
607                 sigaddset(&set, SIGHUP);
608                 sigaddset(&set, SIGINT);
609                 sigaddset(&set, SIGQUIT);
610                 sigaddset(&set, SIGTERM);
611                 SIGPROCMASK(SIG_BLOCK, &set, &oset);
612
613                 annoaux(fd);
614                 if (child_id == OK)
615                         _exit(0);
616
617                 /* reset the signal mask */
618                 SIGPROCMASK(SIG_SETMASK, &oset, &set);
619
620                 chdir(cwd);
621                 break;
622
623         default:  /* no waiting... */
624                 close(fd);
625                 break;
626         }
627 }
628
629
630 static void
631 annoaux(int fd)
632 {
633         int fd2, fd3, msgnum;
634         char *cp, *folder, *maildir;
635         char buffer[BUFSIZ], **ap;
636         FILE *fp;
637         struct msgs *mp;
638
639         if ((folder = getenv("mhfolder")) == NULL || *folder == 0) {
640                 if (debugsw)
641                         admonish(NULL, "$mhfolder not set");
642                 return;
643         }
644         maildir = toabsdir(folder);
645         if (chdir(maildir) == NOTOK) {
646                 if (debugsw)
647                         admonish(maildir, "unable to change directory to");
648                 return;
649         }
650         if (!(mp = folder_read(folder))) {
651                 if (debugsw)
652                         admonish(NULL, "unable to read folder %s", folder);
653                 return;
654         }
655
656         /* check for empty folder */
657         if (mp->nummsg == 0) {
658                 if (debugsw)
659                         admonish(NULL, "no messages in %s", folder);
660                 goto oops;
661         }
662
663         if ((cp = getenv("mhmessages")) == NULL || *cp == 0) {
664                 if (debugsw)
665                         admonish(NULL, "$mhmessages not set");
666                 goto oops;
667         }
668         if (!debugsw  /* MOBY HACK... */
669                         && pushsw
670                         && (fd3 = open("/dev/null", O_RDWR)) != NOTOK
671                         && (fd2 = dup(fileno(stderr))) != NOTOK) {
672                 dup2(fd3, fileno(stderr));
673                 close(fd3);
674         } else
675                 fd2 = NOTOK;
676         for (ap = brkstring(cp = getcpy(cp), " ", NULL); *ap; ap++)
677                 m_convert(mp, *ap);
678         free(cp);
679         if (fd2 != NOTOK)
680                 dup2(fd2, fileno(stderr));
681         if (mp->numsel == 0) {
682                 if (debugsw)
683                         admonish(NULL, "no messages to annotate");
684                 goto oops;
685         }
686
687         lseek(fd, (off_t) 0, SEEK_SET);
688         if ((fp = fdopen(fd, "r")) == NULL) {
689                 if (debugsw)
690                         admonish(NULL, "unable to fdopen annotation list");
691                 goto oops;
692         }
693         cp = NULL;
694         while (fgets(buffer, sizeof(buffer), fp) != NULL)
695                 cp = add(buffer, cp);
696         fclose(fp);
697
698         if (debugsw)
699                 advise(NULL, "annotate%s with %s: \"%s\"",
700                                 inplace ? " inplace" : "", annotext, cp);
701         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
702                 if (is_selected(mp, msgnum)) {
703                         if (debugsw)
704                                 advise(NULL, "annotate message %d", msgnum);
705                         annotate(m_name(msgnum), annotext, cp, inplace,
706                                         1, -2, 0);
707                 }
708         }
709
710         free(cp);
711
712 oops:
713         folder_free(mp);  /* free folder/message structure */
714 }
715
716
717 static void
718 armed_done(int status)
719 {
720         longjmp(env, status ? status : NOTOK);
721
722         exit(status);
723 }