1 /* sendsbr.c -- routines to help WhatNow/Send along
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
9 #include "sbr/fmt_new.h"
13 #include "sbr/m_name.h"
14 #include "sbr/m_getfld.h"
15 #include "sbr/concat.h"
16 #include "sbr/cpydgst.h"
17 #include "sbr/trimcpy.h"
19 #include "sbr/getcpy.h"
20 #include "sbr/m_convert.h"
21 #include "sbr/m_backup.h"
22 #include "sbr/folder_read.h"
23 #include "sbr/folder_free.h"
24 #include "sbr/context_find.h"
25 #include "sbr/brkstring.h"
26 #include "sbr/pidstatus.h"
27 #include "sbr/arglist.h"
28 #include "sbr/error.h"
29 #include "h/fmt_scan.h"
30 #include "h/fmt_compile.h"
31 #include "h/signals.h"
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
48 #include "sbr/m_maildir.h"
49 #include "sbr/m_mktemp.h"
50 #include "sbr/message_id.h"
53 static int setup_oauth_params(char *[], int *, const char *, const char **);
54 #endif /* OAUTH_SUPPORT */
56 int debugsw
= 0; /* global */
63 char *altmsg
= NULL
; /* .. */
64 char *annotext
= NULL
;
65 char *distfile
= NULL
;
72 static void alert (char *, int);
73 static int tmp_fd (void);
74 static void anno (int, struct stat
*);
75 static void annoaux (int);
76 static int sendaux (char **, int, char *, char *, struct stat
*);
77 static void handle_sendfrom(char **, int *, char *, const char *);
78 static int get_from_header_info(const char *, const char **, const char **, const char **);
79 static const char *get_message_header_info(FILE *, char *);
80 static void merge_profile_entry(const char *, const char *, char *[], int *);
81 static void armed_done (int) NORETURN
;
84 * Entry point into (back-end) routines to send message.
88 sendsbr (char **vec
, int vecp
, char *program
, char *draft
, struct stat
*st
,
89 int rename_drft
, const char *auth_svc
)
93 char buffer
[BUFSIZ
], file
[BUFSIZ
];
94 char **buildvec
, *buildprogram
;
95 char *volatile drft
= draft
;
96 /* nvecs is volatile to prevent warning from gcc about possible clobbering
98 volatile int nvecs
= vecp
;
99 int *nvecsp
= (int *) &nvecs
;
102 * Run the mimebuildproc (which is by default mhbuild) on the message
103 * with the addition of the "-auto" flag
106 switch (child
= fork()) {
108 adios("fork", "unable to");
112 buildvec
= argsplit(buildmimeproc
, &buildprogram
, &i
);
113 buildvec
[i
++] = "-auto";
115 buildvec
[i
++] = "-dist";
116 buildvec
[i
++] = (char *) drft
;
118 execvp(buildprogram
, buildvec
);
119 fprintf(stderr
, "unable to exec ");
120 perror(buildmimeproc
);
125 if (pidXwait(child
, buildmimeproc
))
130 set_done(armed_done
);
131 switch (setjmp (env
)) {
134 * If given -push and -unique (which is undocumented), then
135 * rename the draft file. I'm not quite sure why.
137 if (pushsw
&& unique
) {
138 char *cp
= m_mktemp2(drft
, invo_name
, NULL
, NULL
);
140 die("unable to create temporary file");
142 if (rename (drft
, strncpy(file
, cp
, sizeof(file
) - 1)) ==
144 adios (file
, "unable to rename %s to", drft
);
149 * Add in any necessary profile entries for xoauth
155 if (setup_oauth_params(vec
, nvecsp
, auth_svc
, &errmsg
) != OK
) {
159 die("send built without OAUTH_SUPPORT, "
160 "so auth_svc %s is not supported", auth_svc
);
161 #endif /* OAUTH_SUPPORT */
165 * Rework the vec based on From: header in draft, as specified
166 * by sendfrom-address entries in profile.
168 if (context_find_prefix("sendfrom-")) {
169 handle_sendfrom(vec
, nvecsp
, draft
, auth_svc
);
172 status
= sendaux (vec
, nvecs
, program
, drft
, st
) ? NOTOK
: OK
;
174 /* rename the original draft */
175 if (rename_drft
&& status
== OK
&&
176 rename (drft
, strncpy (buffer
, m_backup (drft
),
177 sizeof(buffer
) - 1)) == NOTOK
)
178 advise (buffer
, "unable to rename %s to", drft
);
188 (void) m_unlink (distfile
);
195 * Annotate original message, and
196 * call `postproc' (which is passed down in "program") to send message.
200 sendaux (char **vec
, int vecp
, char *program
, char *drft
, struct stat
*st
)
204 char backup
[BUFSIZ
], buf
[BUFSIZ
];
206 fd
= pushsw
? tmp_fd () : NOTOK
;
210 if ((fd2
= tmp_fd ()) != NOTOK
) {
211 vec
[vecp
++] = "-idanno";
212 snprintf (buf
, sizeof(buf
), "%d", fd2
);
215 inform("unable to create temporary file in %s for "
216 "annotation list, continuing...", get_temp_dir());
220 if (distfile
&& distout (drft
, distfile
, backup
) == NOTOK
)
227 /* oops -- fork error */
228 adios ("fork", "unable to");
229 break; /* NOT REACHED */
233 * child process -- send it
235 * If fd is OK, then we are pushing and fd points to temp
236 * file, so capture anything on stdout and stderr there.
239 dup2 (fd
, fileno (stdout
));
240 dup2 (fd
, fileno (stderr
));
243 execvp (program
, vec
);
244 fprintf (stderr
, "unable to exec ");
250 * parent process -- wait for it
252 if ((status
= pidwait(child_id
, NOTOK
)) == OK
) {
253 if (annotext
&& fd2
!= NOTOK
)
257 * If postproc failed, and we have good fd (which means
258 * we pushed), then mail error message (and possibly the
259 * draft) back to the user.
265 inform("message not delivered to anyone");
267 if (annotext
&& fd2
!= NOTOK
)
270 (void) m_unlink (drft
);
271 if (rename (backup
, drft
) == NOTOK
)
272 advise (drft
, "unable to rename %s to", backup
);
283 * Mail error notification (and possibly a copy of the
284 * message) back to the user, using the mailproc
288 alert (char *file
, int out
)
299 /* oops -- fork error */
300 advise ("fork", "unable to");
304 /* child process -- send it */
305 SIGNAL (SIGHUP
, SIG_IGN
);
306 SIGNAL (SIGINT
, SIG_IGN
);
307 SIGNAL (SIGQUIT
, SIG_IGN
);
308 SIGNAL (SIGTERM
, SIG_IGN
);
310 if ((in
= open (file
, O_RDONLY
)) == NOTOK
) {
311 admonish (file
, "unable to re-open");
313 lseek(out
, 0, SEEK_END
);
314 strncpy (buf
, "\nMessage not delivered to anyone.\n", sizeof(buf
));
315 if (write (out
, buf
, strlen (buf
)) < 0) {
316 advise (file
, "write");
318 strncpy (buf
, "\n------- Unsent Draft\n\n", sizeof(buf
));
319 if (write (out
, buf
, strlen (buf
)) < 0) {
320 advise (file
, "write");
322 cpydgst (in
, out
, file
, "temporary file");
324 strncpy (buf
, "\n------- End of Unsent Draft\n", sizeof(buf
));
325 if (write (out
, buf
, strlen (buf
)) < 0) {
326 advise (file
, "write");
328 if (rename (file
, strncpy (buf
, m_backup (file
),
329 sizeof(buf
) - 1)) == NOTOK
)
330 admonish (buf
, "unable to rename %s to", file
);
333 lseek(out
, 0, SEEK_SET
);
334 dup2 (out
, fileno (stdin
));
336 /* create subject for error notification */
337 snprintf (buf
, sizeof(buf
), "send failed on %s",
338 forwsw
? "enclosed draft" : file
);
340 arglist
= argsplit(mailproc
, &program
, &argp
);
342 arglist
[argp
++] = getusername(1);
343 arglist
[argp
++] = "-subject";
344 arglist
[argp
++] = buf
;
345 arglist
[argp
] = NULL
;
347 execvp (program
, arglist
);
348 fprintf (stderr
, "unable to exec ");
352 default: /* no waiting... */
364 if ((tfile
= m_mktemp2(NULL
, invo_name
, &fd
, NULL
)) == NULL
) return NOTOK
;
367 inform("temporary file %s selected", tfile
);
368 else if (m_unlink (tfile
) == NOTOK
)
369 advise (tfile
, "unable to remove");
376 anno (int fd
, struct stat
*st
)
380 static char *cwd
= NULL
;
384 (stat (altmsg
, &st2
) == NOTOK
385 || st
->st_mtime
!= st2
.st_mtime
386 || st
->st_dev
!= st2
.st_dev
387 || st
->st_ino
!= st2
.st_ino
)) {
389 inform("$mhaltmsg mismatch, continuing...");
393 child_id
= debugsw
? NOTOK
: fork ();
395 case NOTOK
: /* oops */
397 inform("unable to fork, so doing annotations by hand...");
399 cwd
= mh_xstrdup(pwd ());
403 /* block a few signals */
405 sigaddset (&set
, SIGHUP
);
406 sigaddset (&set
, SIGINT
);
407 sigaddset (&set
, SIGQUIT
);
408 sigaddset (&set
, SIGTERM
);
409 sigprocmask (SIG_BLOCK
, &set
, &oset
);
411 unregister_for_removal(0);
417 /* reset the signal mask */
418 sigprocmask (SIG_SETMASK
, &oset
, &set
);
420 if (chdir (cwd
) < 0) {
421 advise (cwd
, "chdir");
425 default: /* no waiting... */
435 int fd2
, fd3
, msgnum
;
436 char *cp
, *folder
, *maildir
;
437 char buffer
[BUFSIZ
], **ap
;
441 if ((folder
= getenv ("mhfolder")) == NULL
|| *folder
== 0) {
443 inform("$mhfolder not set, continuing...");
446 maildir
= m_maildir (folder
);
447 if (chdir (maildir
) == NOTOK
) {
449 admonish (maildir
, "unable to change directory to");
452 if (!(mp
= folder_read (folder
, 0))) {
454 inform("unable to read folder %s, continuing...", folder
);
458 /* check for empty folder */
459 if (mp
->nummsg
== 0) {
461 inform("no messages in %s, continuing...", folder
);
465 if ((cp
= getenv ("mhmessages")) == NULL
|| *cp
== 0) {
467 inform("$mhmessages not set, continuing...");
470 if (!debugsw
/* MOBY HACK... */
472 && (fd3
= open ("/dev/null", O_RDWR
)) != NOTOK
473 && (fd2
= dup (fileno (stderr
))) != NOTOK
) {
474 dup2 (fd3
, fileno (stderr
));
479 for (ap
= brkstring (cp
= mh_xstrdup(cp
), " ", NULL
); *ap
; ap
++)
483 dup2 (fd2
, fileno (stderr
));
484 if (mp
->numsel
== 0) {
486 inform("no messages to annotate, continuing...");
490 lseek(fd
, 0, SEEK_SET
);
491 if ((fp
= fdopen (fd
, "r")) == NULL
) {
493 inform("unable to fdopen annotation list, continuing...");
497 while (fgets (buffer
, sizeof(buffer
), fp
) != NULL
)
498 cp
= add (buffer
, cp
);
502 inform("annotate%s with %s: \"%s\"",
503 inplace
? " inplace" : "", annotext
, cp
);
504 for (msgnum
= mp
->lowsel
; msgnum
<= mp
->hghsel
; msgnum
++) {
505 if (is_selected(mp
, msgnum
)) {
507 inform("annotate message %d", msgnum
);
508 annotate (m_name (msgnum
), annotext
, cp
, inplace
, 1, -2, 0);
515 folder_free (mp
); /* free folder/message structure */
520 handle_sendfrom(char **vec
, int *vecp
, char *draft
, const char *auth_svc
)
522 const char *addr
, *host
;
525 /* Extract address and host from From: header line in draft. */
526 if (get_from_header_info(draft
, &addr
, &host
, &message
) != OK
) {
527 adios(draft
, "%s", message
);
530 /* Merge in any address or host specific switches to post(1) from profile. */
531 merge_profile_entry(addr
, host
, vec
, vecp
);
540 for (vp
= vec
; *vp
; ++vp
) {
541 if (strcmp(*vp
, "xoauth2") == 0) {
543 if (setup_oauth_params(vec
, vecp
, auth_svc
, &message
) != OK
) {
548 NMH_UNUSED(auth_svc
);
549 die("send built without OAUTH_SUPPORT, "
550 "so -saslmech xoauth2 is not supported");
551 #endif /* OAUTH_SUPPORT */
560 * For XOAUTH2, append profile entries so post can do the heavy lifting
563 setup_oauth_params(char *vec
[], int *vecp
, const char *auth_svc
,
564 const char **message
)
566 const char *saslmech
= NULL
, *user
= NULL
;
567 mh_oauth_service_info svc
;
571 /* Make sure we have all the information we need. */
572 for (i
= 1; i
< *vecp
; ++i
) {
573 /* Don't support abbreviated switches, to avoid collisions in the
574 future if new ones are added. */
575 if (! strcmp(vec
[i
-1], "-saslmech")) {
577 } else if (! strcmp(vec
[i
-1], "-user")) {
579 } else if (! strcmp(vec
[i
-1], "-authservice")) {
584 if (auth_svc
== NULL
) {
585 if (saslmech
&& ! strcasecmp(saslmech
, "xoauth2")) {
586 *message
= "must specify -authservice with -saslmech xoauth2";
591 *message
= "must specify -user with -saslmech xoauth2";
595 if (saslmech
&& ! strcasecmp(saslmech
, "xoauth2")) {
596 if (! mh_oauth_get_service_info(auth_svc
, &svc
, errbuf
,
598 die("Unable to retrieve oauth profile entries: %s",
601 vec
[(*vecp
)++] = mh_xstrdup("-authservice");
602 vec
[(*vecp
)++] = mh_xstrdup(auth_svc
);
603 vec
[(*vecp
)++] = mh_xstrdup("-oauthcredfile");
604 vec
[(*vecp
)++] = mh_oauth_cred_fn(auth_svc
);
605 vec
[(*vecp
)++] = mh_xstrdup("-oauthclientid");
606 vec
[(*vecp
)++] = getcpy(svc
.client_id
);
607 vec
[(*vecp
)++] = mh_xstrdup("-oauthclientsecret");
608 vec
[(*vecp
)++] = getcpy(svc
.client_secret
);
609 vec
[(*vecp
)++] = mh_xstrdup("-oauthauthendpoint");
610 vec
[(*vecp
)++] = getcpy(svc
.auth_endpoint
);
611 vec
[(*vecp
)++] = mh_xstrdup("-oauthredirect");
612 vec
[(*vecp
)++] = getcpy(svc
.redirect_uri
);
613 vec
[(*vecp
)++] = mh_xstrdup("-oauthtokenendpoint");
614 vec
[(*vecp
)++] = getcpy(svc
.token_endpoint
);
615 vec
[(*vecp
)++] = mh_xstrdup("-oauthscope");
616 vec
[(*vecp
)++] = getcpy(svc
.scope
);
622 #endif /* OAUTH_SUPPORT */
626 * Extract user and domain from From: header line in draft.
629 get_from_header_info(const char *filename
, const char **addr
, const char **host
, const char **message
)
634 if (stat (filename
, &st
) == NOTOK
) {
635 *message
= "unable to stat draft file";
639 if ((in
= fopen (filename
, "r")) != NULL
) {
640 /* There must be a non-blank Envelope-From or {Resent-}Sender or
641 {Resent-}From header. */
642 char *addrformat
= "%(addr{Envelope-From})";
643 char *hostformat
= "%(host{Envelope-From})";
645 if ((*addr
= get_message_header_info (in
, addrformat
)) == NULL
||
647 addrformat
= distfile
== NULL
? "%(addr{Sender})" : "%(addr{Resent-Sender})";
648 hostformat
= distfile
== NULL
? "%(host{Sender})" : "%(host{Resent-Sender})";
650 if ((*addr
= get_message_header_info (in
, addrformat
)) == NULL
) {
651 addrformat
= distfile
== NULL
? "%(addr{From})" : "%(addr{Resent-From})";
652 hostformat
= distfile
== NULL
? "%(host{From})" : "%(host{Resent-From})";
654 if ((*addr
= get_message_header_info (in
, addrformat
)) == NULL
) {
655 *message
= "unable to find sender address in";
662 /* Use the hostformat that corresponds to the successful addrformat. */
663 if ((*host
= get_message_header_info(in
, hostformat
)) == NULL
) {
664 *message
= "unable to find sender host";
673 *message
= "unable to open";
679 * Get formatted information from header of a message.
680 * Adapted from process_single_file() in uip/fmttest.c.
683 get_message_header_info(FILE *in
, char *format
)
689 m_getfld_state_t gstate
;
690 charstring_t buffer
= charstring_create(0);
693 dat
[0] = dat
[1] = dat
[4] = 0;
694 dat
[2] = fstat(fileno(in
), &st
) == 0 ? st
.st_size
: 0;
697 (void) fmt_compile(new_fs(NULL
, NULL
, format
), &fmt
, 1);
701 * Read in the message and process the header.
704 parsing_header
= true;
705 gstate
= m_getfld_state_init(in
);
707 char name
[NAMESZ
], rbuf
[NMH_BUFSIZ
];
708 int bufsz
= sizeof rbuf
;
709 int state
= m_getfld2(&gstate
, name
, rbuf
, &bufsz
);
714 int bucket
= fmt_addcomptext(name
, rbuf
);
717 while (state
== FLDPLUS
) {
719 state
= m_getfld2(&gstate
, name
, rbuf
, &bufsz
);
720 fmt_appendcomp(bucket
, name
, rbuf
);
724 while (state
== FLDPLUS
) {
726 state
= m_getfld2(&gstate
, name
, rbuf
, &bufsz
);
731 parsing_header
= false;
733 } while (parsing_header
);
734 m_getfld_state_destroy(&gstate
);
736 fmt_scan(fmt
, buffer
, INT_MAX
, dat
, NULL
);
739 /* Trim trailing newline, if any. */
740 retval
= rtrim(charstring_buffer_copy((buffer
)));
741 charstring_free(buffer
);
751 * Look in profile for entry corresponding to addr or host, and add its contents to vec.
753 * Could do some of this automatically, by looking for:
754 * 1) access-$(mbox{from}) in oauth-svc file using mh_oauth_cred_load(), which isn't
755 * static and doesn't have side effects; free the result with mh_oauth_cred_free())
756 * 2) machine $(mbox{from}) in creds
757 * If no -server passed in from profile or commandline, could use smtp.<svc>.com for gmail,
758 * but that might not generalize for other svcs.
761 merge_profile_entry(const char *addr
, const char *host
, char *vec
[], int *vecp
)
763 char *addr_entry
= concat("sendfrom-", addr
, NULL
);
764 char *profile_entry
= context_find(addr_entry
);
767 if (profile_entry
== NULL
) {
768 /* No entry for the user. Look for one for the host. */
769 char *host_entry
= concat("sendfrom-", host
, NULL
);
771 profile_entry
= context_find(host_entry
);
775 /* Use argsplit() to do the real work of splitting the args in the profile entry. */
776 if (profile_entry
&& *profile_entry
) {
779 char **profile_vec
= argsplit(profile_entry
, &file
, &profile_vecp
);
782 for (i
= 0; i
< profile_vecp
; ++i
) {
783 vec
[(*vecp
)++] = getcpy(profile_vec
[i
]);
786 arglist_free(file
, profile_vec
);
792 armed_done (int status
)
794 longjmp (env
, status
? status
: NOTOK
);