2 * sink.c -- forwarding/delivery support for fetchmail
4 * The interface of this module (open_sink(), stuff_line(), close_sink(),
5 * release_sink()) seals off the delivery logic from the protocol machine,
6 * so the latter won't have to care whether it's shipping to an [SL]MTP
7 * listener daemon or an MDA pipe.
9 * Copyright 1998 by Eric S. Raymond
10 * For license terms, see the file COPYING in this directory.
21 #endif /* HAVE_MEMORY_H */
22 #if defined(STDC_HEADERS)
25 #if defined(HAVE_UNISTD_H)
28 #if defined(HAVE_STDARG_H)
36 /* for W* macros after pclose() */
38 #include <sys/types.h>
40 #include <sys/resource.h>
44 #include "fetchmail.h"
49 /* BSD portability hack...I know, this is an ugly place to put it */
50 #if !defined(SIGCHLD) && defined(SIGCLD)
51 #define SIGCHLD SIGCLD
54 /* makes the open_sink()/close_sink() pair non-reentrant */
55 static int lmtp_responses;
57 void smtp_close(struct query *ctl, int sayquit)
58 /* close the socket to SMTP server */
60 if (ctl->smtp_socket != -1)
63 SMTP_quit(ctl->smtp_socket);
64 SockClose(ctl->smtp_socket);
65 ctl->smtp_socket = -1;
70 int smtp_open(struct query *ctl)
71 /* try to open a socket to the appropriate SMTP server for this query */
73 char *parsed_host = NULL;
75 /* maybe it's time to close the socket in order to force delivery */
76 if (NUM_NONZERO(ctl->batchlimit)) {
77 if (batchcount == ctl->batchlimit)
82 /* if no socket to any SMTP host is already set up, try to open one */
83 if (ctl->smtp_socket == -1)
86 * RFC 1123 requires that the domain name in HELO address is a
87 * "valid principal domain name" for the client host. If we're
88 * running in invisible mode, violate this with malice
89 * aforethought in order to make the Received headers and
92 * In fact this code relies on the RFC1123 requirement that the
93 * SMTP listener must accept messages even if verification of the
94 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
96 * How we compute the true mailhost name to pass to the
97 * listener doesn't affect behavior on RFC1123-violating
98 * listeners that check for name match; we're going to lose
99 * on those anyway because we can never give them a name
100 * that matches the local machine fetchmail is running on.
101 * What it will affect is the listener's logging.
104 const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
105 int oldphase = phase;
110 * Run down the SMTP hunt list looking for a server that's up.
111 * Use both explicit hunt entries (value TRUE) and implicit
112 * (default) ones (value FALSE).
115 phase = LISTENER_WAIT;
117 set_timeout(ctl->server.timeout);
118 for (idp = ctl->smtphunt; idp; idp = idp->next)
122 char *portnum = SMTP_PORT;
124 int portnum = SMTP_PORT;
125 #endif /* INET6_ENABLE */
127 xalloca(parsed_host, char *, strlen(idp->id) + 1);
129 ctl->smtphost = idp->id; /* remember last host tried. */
130 if(ctl->smtphost[0]=='/')
131 ctl->listener = LMTP_MODE;
133 strcpy(parsed_host, idp->id);
134 if ((cp = strrchr(parsed_host, '/')))
141 #endif /* INET6_ENABLE */
144 if (ctl->smtphost[0]=='/'){
145 if ((ctl->smtp_socket = UnixOpen(ctl->smtphost))==-1)
148 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
149 ctl->server.plugout)) == -1)
152 /* return immediately for ODMR */
153 if (ctl->server.protocol == P_ODMR)
157 return(ctl->smtp_socket); /* success */
160 /* are we doing SMTP or LMTP? */
161 SMTP_setmode(ctl->listener);
163 /* first, probe for ESMTP */
164 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
165 SMTP_ehlo(ctl->smtp_socket, id_me,
166 ctl->server.esmtp_name, ctl->server.esmtp_password,
167 &ctl->server.esmtp_options) == SM_OK)
171 * RFC 1869 warns that some listeners hang up on a failed EHLO,
172 * so it's safest not to assume the socket will still be good.
176 /* if opening for ESMTP failed, try SMTP */
177 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
178 ctl->server.plugout)) == -1)
181 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
182 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
192 * RFC 1123 requires that the domain name part of the
193 * RCPT TO address be "canonicalized", that is a FQDN
194 * or MX but not a CNAME. Some listeners (like exim)
195 * enforce this. Now that we have the actual hostname,
196 * compute what we should canonicalize with.
198 * make sure we do not forget to drop the /port if
201 if (ctl->listener == LMTP_MODE && !ctl->smtpaddress)
203 if (parsed_host && parsed_host[0] != 0)
204 ctl->destaddr = xstrdup(parsed_host);
206 ctl->destaddr = (ctl->smtphost && ctl->smtphost[0] != '/') ? ctl->smtphost : "localhost";
209 ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost && ctl->smtphost[0] != '/' ? ctl->smtphost : "localhost");
211 if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
212 report(stdout, GT_("forwarding to %s\n"), ctl->smtphost);
214 return(ctl->smtp_socket);
217 static void sanitize(char *s)
222 for (cp = s; (cp = strchr (cp, '\'')); cp++)
226 char *rcpt_address(struct query *ctl, const char *id,
229 static char addr[HOSTLEN+USERNAMELEN+1];
233 snprintf(addr, sizeof (addr), "%s", id);
235 sprintf(addr, "%s", id);
236 #endif /* HAVE_SNPRINTF */
238 else if (usesmtpname && ctl->smtpname)
241 snprintf(addr, sizeof (addr), "%s", ctl->smtpname);
243 sprintf(addr, "%s", ctl->smtpname);
244 #endif /* HAVE_SNPRINTF */
249 snprintf(addr, sizeof (addr), "%s@%s", id, ctl->destaddr);
251 sprintf(addr, "%s@%s", id, ctl->destaddr);
252 #endif /* HAVE_SNPRINTF */
257 static int send_bouncemail(struct query *ctl, struct msgblk *msg,
258 int userclass, char *message,
259 int nerrors, char *errors[])
260 /* bounce back an error report a la RFC 1892 */
262 char daemon_name[18 + HOSTLEN] = "FETCHMAIL-DAEMON@";
263 char boundary[BUFSIZ], *bounce_to;
265 static char *fqdn_of_host = NULL;
266 const char *md1 = "MAILER-DAEMON", *md2 = "MAILER-DAEMON@";
268 /* don't bounce in reply to undeliverable bounces */
269 if (!msg->return_path[0] ||
270 strcmp(msg->return_path, "<>") == 0 ||
271 strcasecmp(msg->return_path, md1) == 0 ||
272 strncasecmp(msg->return_path, md2, strlen(md2)) == 0)
275 bounce_to = (run.bouncemail ? msg->return_path : run.postmaster);
277 SMTP_setmode(SMTP_MODE);
279 /* can't just use fetchmailhost here, it might be localhost */
280 if (fqdn_of_host == NULL)
281 fqdn_of_host = host_fqdn();
282 strcat(daemon_name, fqdn_of_host);
284 /* we need only SMTP for this purpose */
285 if ((sock = SockOpen("localhost", SMTP_PORT, NULL, NULL)) == -1)
288 if (SMTP_ok(sock) != SM_OK)
294 if (SMTP_helo(sock, fetchmailhost) != SM_OK
295 || SMTP_from(sock, daemon_name, (char *)NULL) != SM_OK
296 || SMTP_rcpt(sock, bounce_to) != SM_OK
297 || SMTP_data(sock) != SM_OK)
304 /* our first duty is to keep the sacred foo counters turning... */
306 snprintf(boundary, sizeof(boundary),
309 #endif /* HAVE_SNPRINTF */
310 "foo-mani-padme-hum-%d-%d-%ld",
311 (int)getpid(), (int)getppid(), time((time_t *)NULL));
313 if (outlevel >= O_VERBOSE)
314 report(stdout, GT_("SMTP: (bounce-message body)\n"));
316 /* this will usually go to sylog... */
317 report(stderr, GT_("mail from %s bounced to %s\n"),
318 daemon_name, bounce_to);
320 /* bouncemail headers */
321 SockPrintf(sock, "Return-Path: <>\r\n");
322 SockPrintf(sock, "From: %s\r\n", daemon_name);
323 SockPrintf(sock, "To: %s\r\n", bounce_to);
324 SockPrintf(sock, "MIME-Version: 1.0\r\n");
325 SockPrintf(sock, "Content-Type: multipart/report; report-type=delivery-status;\r\n\tboundary=\"%s\"\r\n", boundary);
326 SockPrintf(sock, "\r\n");
328 /* RFC1892 part 1 -- human-readable message */
329 SockPrintf(sock, "--%s\r\n", boundary);
330 SockPrintf(sock,"Content-Type: text/plain\r\n");
331 SockPrintf(sock, "\r\n");
332 SockWrite(sock, message, strlen(message));
333 SockPrintf(sock, "\r\n");
334 SockPrintf(sock, "\r\n");
341 /* RFC1892 part 2 -- machine-readable responses */
342 SockPrintf(sock, "--%s\r\n", boundary);
343 SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
344 SockPrintf(sock, "\r\n");
345 SockPrintf(sock, "Reporting-MTA: dns; %s\r\n", fetchmailhost);
348 for (idp = msg->recipients; idp; idp = idp->next)
349 if (idp->val.status.mark == userclass)
352 /* Minimum RFC1894 compliance + Diagnostic-Code field */
353 SockPrintf(sock, "\r\n");
354 SockPrintf(sock, "Final-Recipient: rfc822; %s\r\n",
355 rcpt_address (ctl, idp->id, 1));
356 SockPrintf(sock, "Last-Attempt-Date: %s\r\n", rfc822timestamp());
357 SockPrintf(sock, "Action: failed\r\n");
360 /* one error applies to all users */
362 else if (nerrors <= nusers)
364 SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
368 /* errors correspond 1-1 to selected users */
369 error = errors[nusers++];
371 if (strlen(error) > 9 && isdigit(error[4])
372 && error[5] == '.' && isdigit(error[6])
373 && error[7] == '.' && isdigit(error[8]))
374 /* Enhanced status code available, use it */
375 SockPrintf(sock, "Status: %5.5s\r\n", &(error[4]));
377 /* Enhanced status code not available, fake one */
378 SockPrintf(sock, "Status: %c.0.0\r\n", error[0]);
379 SockPrintf(sock, "Diagnostic-Code: %s\r\n", error);
381 SockPrintf(sock, "\r\n");
384 /* RFC1892 part 3 -- headers of undelivered message */
385 SockPrintf(sock, "--%s\r\n", boundary);
386 SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
387 SockPrintf(sock, "\r\n");
388 SockWrite(sock, msg->headers, strlen(msg->headers));
389 SockPrintf(sock, "\r\n");
390 SockPrintf(sock, "--%s--\r\n", boundary);
392 if (SMTP_eom(sock) != SM_OK || SMTP_quit(sock))
403 static int handle_smtp_report(struct query *ctl, struct msgblk *msg)
404 /* handle SMTP errors based on the content of SMTP_response */
405 /* return of PS_REFUSED deletes mail from the server; PS_TRANSIENT keeps it */
407 int smtperr = atoi(smtp_response);
410 xalloca(responses[0], char *, strlen(smtp_response)+1);
411 strcpy(responses[0], smtp_response);
415 * Don't do this! It can really mess you up if, for example, you're
416 * reporting an error with a single RCPT TO address among several;
417 * RSET discards the message body and it doesn't get sent to the
420 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
421 if (outlevel >= O_DEBUG)
422 report(stdout, GT_("Saved error is still %d\n"), smtperr);
423 #endif /* __UNUSED */
426 * Note: send_bouncemail message strings are not made subject
427 * to gettext translation because (a) they're going to be
428 * embedded in a text/plain 7bit part, and (b) they're
429 * going to be associated with listener error-response
430 * messages, which are probably in English (none of the
431 * MTAs I know about are internationalized).
433 if (str_find(&ctl->antispam, smtperr))
436 * SMTP listener explicitly refuses to deliver mail
437 * coming from this address, probably due to an
438 * anti-spam domain exclusion. Respect this. Don't
439 * try to ship the message, and don't prevent it from
440 * being deleted. There's no point in bouncing the
441 * email either since most spammers don't put their
442 * real return email address anywhere in the headers
443 * (unless the user insists with the SET SPAMBOUNCE
448 * 571 = sendmail's "unsolicited email refused"
449 * 550 = exim's new antispam response (temporary)
450 * 501 = exim's old antispam response
451 * 554 = Postfix antispam response.
458 snprintf(rejmsg, sizeof(rejmsg),
461 #endif /* HAVE_SNPRINTF */
462 "spam filter or virus scanner rejected message because:\r\n"
463 "%s\r\n", responses[0]);
465 send_bouncemail(ctl, msg, XMIT_ACCEPT,
466 rejmsg, 1, responses);
472 * Suppress error message only if the response specifically
473 * meant `excluded for policy reasons'. We *should* see
474 * an error when the return code is less specific.
477 report(stderr, GT_("%cMTP error: %s\n"),
483 case 552: /* message exceeds fixed maximum message size */
485 * Permanent no-go condition on the
486 * ESMTP server. Don't try to ship the message,
487 * and allow it to be deleted.
490 send_bouncemail(ctl, msg, XMIT_ACCEPT,
491 "This message was too large (SMTP error 552).\r\n",
495 case 553: /* invalid sending domain */
497 * These latter days 553 usually means a spammer is trying to
498 * cover his tracks. We never bouncemail on these, because
499 * (a) the return address is invalid by definition, and
500 * (b) we wouldn't want spammers to get confirmation that
501 * this address is live, anyway.
503 #ifdef __DONT_FEED_THE_SPAMMERS__
505 send_bouncemail(ctl, msg, XMIT_ACCEPT,
506 "Invalid address in MAIL FROM (SMTP error 553).\r\n",
508 #endif /* __DONT_FEED_THE_SPAMMERS__ */
512 /* bounce non-transient errors back to the sender */
513 if (smtperr >= 500 && smtperr <= 599)
514 if (send_bouncemail(ctl, msg, XMIT_ACCEPT,
515 "General SMTP/ESMTP error.\r\n",
517 return(run.bouncemail ? PS_REFUSED : PS_TRANSIENT);
519 * We're going to end up here on 4xx errors, like:
521 * 451: temporarily unable to identify sender (exim)
522 * 452: temporary out-of-queue-space condition on the ESMTP server.
524 * These are temporary errors. Don't try to ship the message,
525 * and suppress deletion so it can be retried on a future
528 * Bouncemail *might* be appropriate here as a delay
529 * notification (note; if we ever add this, we must make
530 * sure the RFC1894 Action field is "delayed" rather than
531 * "failed"). But it's not really necessary because
532 * these are not actual failures, we're very likely to be
533 * able to recover on the next cycle.
535 return(PS_TRANSIENT);
539 static int handle_smtp_report_without_bounce(struct query *ctl, struct msgblk *msg)
540 /* handle SMTP errors based on the content of SMTP_response */
541 /* atleast one PS_TRANSIENT: do not send the bounce mail, keep the mail;
542 * no PS_TRANSIENT, atleast one PS_SUCCESS: send the bounce mail, delete the mail;
543 * no PS_TRANSIENT, no PS_SUCCESS: do not send the bounce mail, delete the mail */
545 int smtperr = atoi(smtp_response);
547 if (str_find(&ctl->antispam, smtperr))
555 report(stderr, GT_("%cMTP error: %s\n"),
561 case 552: /* message exceeds fixed maximum message size */
566 case 553: /* invalid sending domain */
567 #ifdef __DONT_FEED_THE_SPAMMERS__
570 #endif /* __DONT_FEED_THE_SPAMMERS__ */
574 /* bounce non-transient errors back to the sender */
575 if (smtperr >= 500 && smtperr <= 599)
577 return(PS_TRANSIENT);
581 /* these are shared by open_sink and stuffline */
584 int stuffline(struct query *ctl, char *buf)
585 /* ship a line to the given control block's output sink (SMTP server or MDA) */
590 /* The line may contain NUL characters. Find the last char to use
591 * -- the real line termination is the sequence "\n\0".
593 last = buf + 1; /* last[-1] must be valid! */
594 while ((last += strlen(last)) && (last[-1] != '\n'))
597 /* fix message lines that have only \n termination (for qmail) */
600 if (last - 1 == buf || last[-2] != '\r')
609 phase = FORWARDING_WAIT;
612 * SMTP byte-stuffing. We only do this if the protocol does *not*
613 * use .<CR><LF> as EOM. If it does, the server will already have
614 * decorated any . lines it sends back up.
618 if (ctl->server.base_protocol->delimited) /* server has already byte-stuffed */
623 /* writing to SMTP, leave the byte-stuffing in place */;
625 else /* if (!protocol->delimited) -- not byte-stuffed already */
628 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
630 /* leave it alone */;
634 /* we may need to strip carriage returns */
639 for (sp = tp = buf; sp < last; sp++)
647 if (ctl->mda || ctl->bsmtp)
648 n = fwrite(buf, 1, last - buf, sinkfp);
649 else if (ctl->smtp_socket != -1)
650 n = SockWrite(ctl->smtp_socket, buf, last - buf);
657 static int open_bsmtp_sink(struct query *ctl, struct msgblk *msg,
658 int *good_addresses, int *bad_addresses)
659 /* open a BSMTP stream */
663 if (strcmp(ctl->bsmtp, "-") == 0)
666 sinkfp = fopen(ctl->bsmtp, "a");
668 /* see the ap computation under the SMTP branch */
670 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
672 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
673 fputs(" BODY=8BITMIME", sinkfp);
674 else if (ctl->mimemsg & MSG_IS_7BIT)
675 fputs(" BODY=7BIT", sinkfp);
677 /* exim's BSMTP processor does not handle SIZE */
678 /* fprintf(sinkfp, " SIZE=%d", msg->reallen); */
680 fprintf(sinkfp, "\r\n");
683 * RFC 1123 requires that the domain name part of the
684 * RCPT TO address be "canonicalized", that is a FQDN
685 * or MX but not a CNAME. Some listeners (like exim)
686 * enforce this. Now that we have the actual hostname,
687 * compute what we should canonicalize with.
689 ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
692 for (idp = msg->recipients; idp; idp = idp->next)
693 if (idp->val.status.mark == XMIT_ACCEPT)
695 fprintf(sinkfp, "RCPT TO: %s\r\n",
696 rcpt_address (ctl, idp->id, 1));
700 fputs("DATA\r\n", sinkfp);
704 report(stderr, GT_("BSMTP file open or preamble write failed\n"));
711 /* this is experimental and will be removed if double bounces are reported */
712 #define EXPLICIT_BOUNCE_ON_BAD_ADDRESS
715 static const char *is_quad(const char *q)
716 /* Check if the string passed in points to what could be one quad of a
717 * dotted-quad IP address. Requirements are that the string is not a
718 * NULL pointer, begins with a period (which is skipped) or a digit
719 * and ends with a period or a NULL. If these requirements are met, a
720 * pointer to the last character (the period or the NULL character) is
721 * returned; otherwise NULL.
730 for(r=q;isdigit(*r);r++)
732 if ( ((*r) && (*r != '.')) || ((r-q) < 1) || ((r-q)>3) )
734 /* Make sure quad is < 255 */
743 else if (*(q+1) == '5')
753 static int is_dottedquad(const char *hostname)
754 /* Returns a true value if the passed in string looks like an IP
755 * address in dotted-quad form, and a false value otherwise.
759 return ((hostname=is_quad(is_quad(is_quad(is_quad(hostname))))) != NULL) &&
763 static int open_smtp_sink(struct query *ctl, struct msgblk *msg,
764 int *good_addresses, int *bad_addresses)
765 /* open an SMTP stream */
769 char options[MSGBUFSIZE];
770 char addr[HOSTLEN+USERNAMELEN+1];
771 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
772 char **from_responses;
773 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
775 int force_transient_error = 0;
779 * Compute ESMTP options.
782 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
783 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
784 strcpy(options, " BODY=8BITMIME");
785 else if (ctl->mimemsg & MSG_IS_7BIT)
786 strcpy(options, " BODY=7BIT");
789 if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
790 sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
793 * Try to get the SMTP listener to take the Return-Path
794 * address as MAIL FROM. If it won't, fall back on the
795 * remotename and mailserver host. This won't affect replies,
796 * which use the header From address anyway; the MAIL FROM
797 * address is a place for the SMTP listener to send
798 * bouncemail. The point is to guarantee a FQDN in the MAIL
799 * FROM line -- some SMTP listeners, like smail, become
802 * RFC 1123 requires that the domain name part of the
803 * MAIL FROM address be "canonicalized", that is a
804 * FQDN or MX but not a CNAME. We'll assume the Return-Path
805 * header is already in this form here (it certainly
806 * is if rewrite is on). RFC 1123 is silent on whether
807 * a nonexistent hostname part is considered canonical.
809 * This is a potential problem if the MTAs further upstream
810 * didn't pass canonicalized From/Return-Path lines, *and* the
811 * local SMTP listener insists on them.
813 * Handle the case where an upstream MTA is setting a return
814 * path equal to "@". Ghod knows why anyone does this, but
815 * it's been reported to happen in mail from Amazon.com and
818 * Also, if the hostname is a dotted quad, wrap it in square brackets.
819 * Apparently this is required by RFC2821, section 4.1.3.
821 if (!msg->return_path[0] || (msg->return_path[0] == '@'))
823 if (is_dottedquad(ctl->server.truename))
826 snprintf(addr, sizeof(addr),
829 #endif /* HAVE_SNPRINTF */
830 "%s@[%s]", ctl->remotename, ctl->server.truename);
835 snprintf(addr, sizeof(addr),
838 #endif /* HAVE_SNPRINTF */
839 "%s@%s", ctl->remotename, ctl->server.truename);
843 else if (strchr(msg->return_path,'@') || strchr(msg->return_path,'!'))
844 ap = msg->return_path;
845 else /* in case Return-Path existed but was local */
847 if (is_dottedquad(ctl->server.truename))
850 snprintf(addr, sizeof(addr),
853 #endif /* HAVE_SNPRINTF */
854 "%s@[%s]", msg->return_path, ctl->server.truename);
859 snprintf(addr, sizeof(addr),
862 #endif /* HAVE_SNPRINTF */
863 "%s@%s", msg->return_path, ctl->server.truename);
868 if ((smtp_err = SMTP_from(ctl->smtp_socket, ap, options)) == SM_UNRECOVERABLE)
871 return(PS_TRANSIENT);
873 if (smtp_err != SM_OK)
875 int err = handle_smtp_report(ctl, msg);
877 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
882 * Now list the recipient addressees
885 for (idp = msg->recipients; idp; idp = idp->next)
887 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
888 xalloca(from_responses, char **, sizeof(char *) * total_addresses);
889 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
890 for (idp = msg->recipients; idp; idp = idp->next)
891 if (idp->val.status.mark == XMIT_ACCEPT)
894 address = rcpt_address (ctl, idp->id, 1);
895 if ((smtp_err = SMTP_rcpt(ctl->smtp_socket, address)) == SM_UNRECOVERABLE)
898 return(PS_TRANSIENT);
900 if (smtp_err == SM_OK)
904 switch (handle_smtp_report_without_bounce(ctl, msg))
907 force_transient_error = 1;
911 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
912 xalloca(from_responses[*bad_addresses],
914 strlen(smtp_response)+1);
915 strcpy(from_responses[*bad_addresses], smtp_response);
916 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
919 idp->val.status.mark = XMIT_RCPTBAD;
920 if (outlevel >= O_VERBOSE)
922 GT_("%cMTP listener doesn't like recipient address `%s'\n"),
923 ctl->listener, address);
927 if (outlevel >= O_VERBOSE)
929 GT_("%cMTP listener doesn't really like recipient address `%s'\n"),
930 ctl->listener, address);
936 if (force_transient_error) {
937 /* do not risk dataloss due to overengineered multidrop
938 * crap. If one of the recipients returned PS_TRANSIENT,
939 * we return exactly that.
941 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
942 return(PS_TRANSIENT);
944 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
946 * This should not be necessary, because the SMTP listener itself
947 * should genrate a bounce for the bad address.
950 send_bouncemail(ctl, msg, XMIT_RCPTBAD,
951 "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
952 *bad_addresses, from_responses);
953 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
956 * It's tempting to do local notification only if bouncemail was
957 * insufficient -- that is, to add && total_addresses > *bad_addresses
958 * to the test here. The problem with this theory is that it would
959 * make initial diagnosis of a broken multidrop configuration very
960 * hard -- most single-recipient messages would just invisibly bounce.
962 if (!(*good_addresses))
964 if (!run.postmaster[0])
966 if (outlevel >= O_VERBOSE)
967 report(stderr, GT_("no address matches; no postmaster set.\n"));
968 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
971 if ((smtp_err = SMTP_rcpt(ctl->smtp_socket,
972 rcpt_address (ctl, run.postmaster, 0))) == SM_UNRECOVERABLE)
975 return(PS_TRANSIENT);
977 if (smtp_err != SM_OK)
979 report(stderr, GT_("can't even send to %s!\n"), run.postmaster);
980 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
984 if (outlevel >= O_VERBOSE)
985 report(stderr, GT_("no address matches; forwarding to %s.\n"), run.postmaster);
989 * Tell the listener we're ready to send data.
990 * Some listeners (like zmailer) may return antispam errors here.
992 if ((smtp_err = SMTP_data(ctl->smtp_socket)) == SM_UNRECOVERABLE)
995 return(PS_TRANSIENT);
997 if (smtp_err != SM_OK)
999 int err = handle_smtp_report(ctl, msg);
1000 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1005 * We need to stash this away in order to know how many
1006 * response lines to expect after the LMTP end-of-message.
1008 lmtp_responses = *good_addresses;
1013 static int open_mda_sink(struct query *ctl, struct msgblk *msg,
1014 int *good_addresses, int *bad_addresses)
1015 /* open a stream to a local MDA */
1019 #endif /* HAVE_SETEUID */
1021 int length = 0, fromlen = 0, nameslen = 0;
1022 char *names = NULL, *before, *after, *from = NULL;
1024 ctl->destaddr = "localhost";
1026 for (idp = msg->recipients; idp; idp = idp->next)
1027 if (idp->val.status.mark == XMIT_ACCEPT)
1028 (*good_addresses)++;
1030 length = strlen(ctl->mda);
1031 before = xstrdup(ctl->mda);
1033 /* get user addresses for %T (or %s for backward compatibility) */
1034 if (strstr(before, "%s") || strstr(before, "%T"))
1037 * We go through this in order to be able to handle very
1038 * long lists of users and (re)implement %s.
1041 for (idp = msg->recipients; idp; idp = idp->next)
1042 if ((idp->val.status.mark == XMIT_ACCEPT))
1043 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1044 if ((*good_addresses == 0))
1045 nameslen = strlen(run.postmaster);
1047 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1048 if (*good_addresses == 0)
1049 strcpy(names, run.postmaster);
1053 for (idp = msg->recipients; idp; idp = idp->next)
1054 if (idp->val.status.mark == XMIT_ACCEPT)
1056 strcat(names, idp->id);
1059 names[--nameslen] = '\0'; /* chop trailing space */
1065 /* get From address for %F */
1066 if (strstr(before, "%F"))
1068 from = xstrdup(msg->return_path);
1072 fromlen = strlen(from);
1075 /* do we have to build an mda string? */
1080 /* find length of resulting mda string */
1082 while ((sp = strstr(sp, "%s"))) {
1083 length += nameslen; /* subtract %s and add '' */
1087 while ((sp = strstr(sp, "%T"))) {
1088 length += nameslen; /* subtract %T and add '' */
1092 while ((sp = strstr(sp, "%F"))) {
1093 length += fromlen; /* subtract %F and add '' */
1097 after = xmalloc(length + 1);
1099 /* copy mda source string to after, while expanding %[sTF] */
1100 for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
1101 if (sp[0] != '%') continue;
1103 /* need to expand? BTW, no here overflow, because in
1104 ** the worst case (end of string) sp[1] == '\0' */
1105 if (sp[1] == 's' || sp[1] == 'T') {
1110 sp++; /* position sp over [sT] */
1111 dp--; /* adjust dp */
1112 } else if (sp[1] == 'F') {
1117 sp++; /* position sp over F */
1118 dp--; /* adjust dp */
1137 if (outlevel >= O_DEBUG)
1138 report(stdout, GT_("about to deliver with: %s\n"), before);
1142 * Arrange to run with user's permissions if we're root.
1143 * This will initialize the ownership of any files the
1144 * MDA creates properly. (The seteuid call is available
1145 * under all BSDs and Linux)
1147 orig_uid = getuid();
1149 #endif /* HAVE_SETEUID */
1151 sinkfp = popen(before, "w");
1156 /* this will fail quietly if we didn't start as root */
1158 #endif /* HAVE_SETEUID */
1162 report(stderr, GT_("MDA open failed\n"));
1167 * We need to disable the normal SIGCHLD handling here because
1168 * sigchld_handler() would reap away the error status, returning
1169 * error status instead of 0 for successful completion.
1171 set_signal_handler(SIGCHLD, SIG_DFL);
1176 int open_sink(struct query *ctl, struct msgblk *msg,
1177 int *good_addresses, int *bad_addresses)
1178 /* set up sinkfp to be an input sink we can ship a message to */
1180 *bad_addresses = *good_addresses = 0;
1182 if (ctl->bsmtp) /* dump to a BSMTP batch file */
1183 return(open_bsmtp_sink(ctl, msg, good_addresses, bad_addresses));
1185 * Try to forward to an SMTP or LMTP listener. If the attempt to
1186 * open a socket fails, fall through to attempt delivery via
1189 else if (!ctl->mda && smtp_open(ctl) != -1)
1190 return(open_smtp_sink(ctl, msg, good_addresses, bad_addresses));
1193 * Awkward case. User didn't specify an MDA. Our attempt to get a
1194 * listener socket failed. Try to cope anyway -- initial configuration
1195 * may have found procmail.
1199 report(stderr, GT_("%cMTP connect to %s failed\n"),
1201 ctl->smtphost ? ctl->smtphost : "localhost");
1203 #ifndef FALLBACK_MDA
1204 /* No fallback MDA declared. Bail out. */
1208 * If user had things set up to forward offsite, no way
1209 * we want to deliver locally!
1211 if (ctl->smtphost && strcmp(ctl->smtphost, "localhost"))
1215 * User was delivering locally. We have a fallback MDA.
1216 * Latch it in place, logging the error, and fall through.
1217 * Set stripcr as we would if MDA had been the initial transport
1219 ctl->mda = FALLBACK_MDA;
1221 ctl->stripcr = TRUE;
1223 report(stderr, GT_("can't raise the listener; falling back to %s"),
1228 if (ctl->mda) /* must deliver through an MDA */
1229 return(open_mda_sink(ctl, msg, good_addresses, bad_addresses));
1234 void release_sink(struct query *ctl)
1235 /* release the per-message output sink, whether it's a pipe or SMTP socket */
1237 if (ctl->bsmtp && sinkfp)
1239 if (strcmp(ctl->bsmtp, "-"))
1242 sinkfp = (FILE *)NULL;
1250 sinkfp = (FILE *)NULL;
1252 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1256 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
1257 /* perform end-of-message actions on the current output sink */
1264 /* close the delivery pipe, we'll reopen before next message */
1267 rc = pclose(sinkfp);
1268 sinkfp = (FILE *)NULL;
1273 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1277 if (WIFSIGNALED(rc)) {
1279 GT_("MDA died of signal %d\n"), WTERMSIG(rc));
1280 } else if (WIFEXITED(rc)) {
1282 GT_("MDA returned nonzero status %d\n"), WEXITSTATUS(rc));
1285 GT_("Strange: MDA pclose returned %d, cannot handle at %s:%d\n"), rc, __FILE__, __LINE__);
1291 else if (ctl->bsmtp && sinkfp)
1295 /* implicit disk-full check here... */
1296 fputs(".\r\n", sinkfp);
1297 error = ferror(sinkfp);
1298 if (strcmp(ctl->bsmtp, "-"))
1300 if (fclose(sinkfp) == EOF) error = 1;
1301 sinkfp = (FILE *)NULL;
1306 GT_("Message termination or close of BSMTP file failed\n"));
1312 /* write message terminator */
1313 if ((smtp_err = SMTP_eom(ctl->smtp_socket)) == SM_UNRECOVERABLE)
1318 if (smtp_err != SM_OK)
1320 if (handle_smtp_report(ctl, msg) != PS_REFUSED)
1322 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1327 report(stderr, GT_("SMTP listener refused delivery\n"));
1328 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1334 * If this is an SMTP connection, SMTP_eom() ate the response.
1335 * But could be this is an LMTP connection, in which case we have to
1336 * interpret either (a) a single 503 response meaning there
1337 * were no successful RCPT TOs, or (b) a variable number of
1338 * responses, one for each successful RCPT TO. We need to send
1339 * bouncemail on each failed response and then return TRUE anyway,
1340 * otherwise the message will get left in the queue and resent
1341 * to people who got it the first time.
1343 if (ctl->listener == LMTP_MODE)
1345 if (lmtp_responses == 0)
1347 SMTP_ok(ctl->smtp_socket);
1350 * According to RFC2033, 503 is the only legal response
1351 * if no RCPT TO commands succeeded. No error recovery
1352 * is really possible here, as we have no idea what
1353 * insane thing the listener might be doing if it doesn't
1356 if (atoi(smtp_response) == 503)
1357 report(stderr, GT_("LMTP delivery error on EOM\n"));
1360 GT_("Unexpected non-503 response to LMTP EOM: %s\n"),
1364 * It's not completely clear what to do here. We choose to
1365 * interpret delivery failure here as a transient error,
1366 * the same way SMTP delivery failure is handled. If we're
1367 * wrong, an undead message will get stuck in the queue.
1376 /* eat the RFC2033-required responses, saving errors */
1377 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
1378 for (errors = i = 0; i < lmtp_responses; i++)
1380 if ((smtp_err = SMTP_ok(ctl->smtp_socket)) == SM_UNRECOVERABLE)
1385 if (smtp_err == SM_OK)
1386 responses[i] = (char *)NULL;
1389 xalloca(responses[errors],
1391 strlen(smtp_response)+1);
1392 strcpy(responses[errors], smtp_response);
1398 return(TRUE); /* all deliveries succeeded */
1401 * One or more deliveries failed.
1402 * If we can bounce a failures list back to the
1403 * sender, and the postmaster does not want to
1404 * deal with the bounces return TRUE, deleting the
1405 * message from the server so it won't be
1406 * re-forwarded on subsequent poll cycles.
1408 return(send_bouncemail(ctl, msg, XMIT_ACCEPT,
1409 "LSMTP partial delivery failure.\r\n",
1410 errors, responses));
1418 int open_warning_by_mail(struct query *ctl, struct msgblk *msg)
1419 /* set up output sink for a mailed warning to calling user */
1424 * Dispatching warning email is a little complicated. The problem is
1425 * that we have to deal with three distinct cases:
1427 * 1. Single-drop running from user account. Warning mail should
1428 * go to the local name for which we're collecting (coincides
1429 * with calling user).
1431 * 2. Single-drop running from root or other privileged ID, with rc
1432 * file generated on the fly (Ken Estes's weird setup...) Mail
1433 * should go to the local name for which we're collecting (does not
1434 * coincide with calling user).
1436 * 3. Multidrop. Mail must go to postmaster. We leave the recipients
1437 * member null so this message will fall through to run.postmaster.
1439 * The zero in the reallen element means we won't pass a SIZE
1440 * option to ESMTP; the message length would be more trouble than
1441 * it's worth to compute.
1443 struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON@", 0};
1446 strcat(reply.return_path, ctl->smtpaddress ? ctl->smtpaddress :
1449 if (!MULTIDROP(ctl)) /* send to calling user */
1451 save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
1452 status = open_sink(ctl, &reply, &good, &bad);
1453 free_str_list(&reply.recipients);
1455 else /* send to postmaster */
1456 status = open_sink(ctl, &reply, &good, &bad);
1457 stuff_warning(ctl, "Date: %s", rfc822timestamp());
1461 #if defined(HAVE_STDARG_H)
1462 void stuff_warning(struct query *ctl, const char *fmt, ... )
1464 void stuff_warning(struct query *ctl, fmt, va_alist)
1466 const char *fmt; /* printf-style format */
1469 /* format and ship a warning message line by mail */
1471 char buf[MSGBUFSIZE+4];
1475 * stuffline() requires its input to be writeable (for CR stripping),
1476 * so we needed to copy the message to a writeable buffer anyway in
1477 * case it was a string constant. We make a virtue of that necessity
1478 * here by supporting stdargs/varargs.
1480 #if defined(HAVE_STDARG_H)
1485 #ifdef HAVE_VSNPRINTF
1486 vsnprintf(buf, sizeof(buf), fmt, ap);
1488 vsprintf(buf, fmt, ap);
1492 #ifdef HAVE_SNPRINTF
1493 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1495 strcat(buf, "\r\n");
1496 #endif /* HAVE_SNPRINTF */
1498 /* guard against very long lines */
1499 buf[MSGBUFSIZE+1] = '\r';
1500 buf[MSGBUFSIZE+2] = '\n';
1501 buf[MSGBUFSIZE+3] = '\0';
1503 stuffline(ctl, buf);
1506 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
1507 /* sign and send mailed warnings */
1509 stuff_warning(ctl, GT_("--\n\t\t\t\tThe Fetchmail Daemon\n"));
1510 close_sink(ctl, msg, TRUE);
1513 /* sink.c ends here */