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.
20 #endif /* HAVE_MEMORY_H */
21 #if defined(STDC_HEADERS)
24 #if defined(HAVE_UNISTD_H)
27 #if defined(HAVE_STDARG_H)
34 /* for W* macros after pclose() */
36 #include <sys/types.h>
37 #include <sys/resource.h>
41 #include "fetchmail.h"
46 /* BSD portability hack...I know, this is an ugly place to put it */
47 #if !defined(SIGCHLD) && defined(SIGCLD)
48 #define SIGCHLD SIGCLD
51 /* makes the open_sink()/close_sink() pair non-reentrant */
52 static int lmtp_responses;
54 void smtp_close(struct query *ctl, int sayquit)
55 /* close the socket to SMTP server */
57 if (ctl->smtp_socket != -1)
60 SMTP_quit(ctl->smtp_socket);
61 SockClose(ctl->smtp_socket);
62 ctl->smtp_socket = -1;
67 int smtp_open(struct query *ctl)
68 /* try to open a socket to the appropriate SMTP server for this query */
70 char *parsed_host = NULL;
72 /* maybe it's time to close the socket in order to force delivery */
73 if (last_smtp_ok > 0 && time((time_t *)NULL) - last_smtp_ok > mytimeout)
78 if (NUM_NONZERO(ctl->batchlimit)) {
79 if (batchcount == ctl->batchlimit)
84 /* if no socket to any SMTP host is already set up, try to open one */
85 if (ctl->smtp_socket == -1)
88 * RFC 1123 requires that the domain name in HELO address is a
89 * "valid principal domain name" for the client host. If we're
90 * running in invisible mode, violate this with malice
91 * aforethought in order to make the Received headers and
94 * In fact this code relies on the RFC1123 requirement that the
95 * SMTP listener must accept messages even if verification of the
96 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
98 * How we compute the true mailhost name to pass to the
99 * listener doesn't affect behavior on RFC1123-violating
100 * listeners that check for name match; we're going to lose
101 * on those anyway because we can never give them a name
102 * that matches the local machine fetchmail is running on.
103 * What it will affect is the listener's logging.
106 const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
107 int oldphase = phase;
112 * Run down the SMTP hunt list looking for a server that's up.
113 * Use both explicit hunt entries (value TRUE) and implicit
114 * (default) ones (value FALSE).
117 phase = LISTENER_WAIT;
119 set_timeout(ctl->server.timeout);
120 for (idp = ctl->smtphunt; idp; idp = idp->next)
124 char *portnum = SMTP_PORT;
126 int portnum = SMTP_PORT;
127 #endif /* INET6_ENABLE */
129 xalloca(parsed_host, char *, strlen(idp->id) + 1);
131 ctl->smtphost = idp->id; /* remember last host tried. */
132 if(ctl->smtphost[0]=='/')
133 ctl->listener = LMTP_MODE;
135 strcpy(parsed_host, idp->id);
136 if ((cp = strrchr(parsed_host, '/')))
143 #endif /* INET6_ENABLE */
146 if (ctl->smtphost[0]=='/'){
147 if ((ctl->smtp_socket = UnixOpen(ctl->smtphost))==-1)
150 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
151 ctl->server.plugout)) == -1)
154 /* return immediately for ODMR */
155 if (ctl->server.protocol == P_ODMR)
159 return(ctl->smtp_socket); /* success */
162 /* are we doing SMTP or LMTP? */
163 SMTP_setmode(ctl->listener);
165 /* first, probe for ESMTP */
166 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
167 SMTP_ehlo(ctl->smtp_socket, id_me,
168 ctl->server.esmtp_name, ctl->server.esmtp_password,
169 &ctl->server.esmtp_options) == SM_OK)
173 * RFC 1869 warns that some listeners hang up on a failed EHLO,
174 * so it's safest not to assume the socket will still be good.
178 /* if opening for ESMTP failed, try SMTP */
179 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
180 ctl->server.plugout)) == -1)
183 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
184 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
194 * RFC 1123 requires that the domain name part of the
195 * RCPT TO address be "canonicalized", that is a FQDN
196 * or MX but not a CNAME. Some listeners (like exim)
197 * enforce this. Now that we have the actual hostname,
198 * compute what we should canonicalize with.
200 * make sure we do not forget to drop the /port if
203 if (ctl->listener == LMTP_MODE && !ctl->smtpaddress)
205 if (parsed_host && parsed_host[0] != 0)
206 ctl->destaddr = xstrdup(parsed_host);
208 ctl->destaddr = (ctl->smtphost && ctl->smtphost[0] != '/') ? ctl->smtphost : "localhost";
213 * Here we try to find a correct domain name part for the RCPT
214 * TO address. If smtpaddress is set, no need to guestimate
215 * it. Otherwise, using ctl->smtphost as a base is a good
216 * base, although we may have to strip any port appended to
217 * communicate with SMTP servers that do not listen on the
218 * SMTP port. (benj) */
219 if (ctl->smtpaddress)
220 ctl->destaddr = ctl->smtpaddress;
221 else if (ctl->smtphost && ctl->smtphost[0] != '/')
224 if ((cp = strchr (ctl->smtphost, '/')))
226 /* As an alternate port for smtphost is specified, we
227 need to strip it from domain name. */
229 xalloca(smtpname, char *, cp - ctl->smtphost + 1);
230 strncpy(smtpname, ctl->smtphost, cp - ctl->smtphost +1);
231 cp = strchr(smtpname, '/');
233 ctl->destaddr = smtpname;
236 /* No need to strip port, domain name is smtphost. */
237 ctl->destaddr = ctl->smtphost;
239 /* No smtphost is specified or it is a UNIX socket, then use
240 localhost as a domain part. */
242 ctl->destaddr = "localhost";
245 if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
246 report(stdout, GT_("forwarding to %s\n"), ctl->smtphost);
248 return(ctl->smtp_socket);
251 static void sanitize(char *s)
256 for (cp = s; (cp = strchr (cp, '\'')); cp++)
260 char *rcpt_address(struct query *ctl, const char *id,
263 static char addr[HOSTLEN+USERNAMELEN+1];
267 snprintf(addr, sizeof (addr), "%s", id);
269 sprintf(addr, "%s", id);
270 #endif /* HAVE_SNPRINTF */
272 else if (usesmtpname && ctl->smtpname)
275 snprintf(addr, sizeof (addr), "%s", ctl->smtpname);
277 sprintf(addr, "%s", ctl->smtpname);
278 #endif /* HAVE_SNPRINTF */
283 snprintf(addr, sizeof (addr), "%s@%s", id, ctl->destaddr);
285 sprintf(addr, "%s@%s", id, ctl->destaddr);
286 #endif /* HAVE_SNPRINTF */
291 static int send_bouncemail(struct query *ctl, struct msgblk *msg,
292 int userclass, char *message,
293 int nerrors, char *errors[])
294 /* bounce back an error report a la RFC 1892 */
296 char daemon_name[18 + HOSTLEN] = "FETCHMAIL-DAEMON@";
297 char boundary[BUFSIZ], *bounce_to;
299 static char *fqdn_of_host = NULL;
300 const char *md1 = "MAILER-DAEMON", *md2 = "MAILER-DAEMON@";
302 /* don't bounce in reply to undeliverable bounces */
303 if (!msg->return_path[0] ||
304 strcmp(msg->return_path, "<>") == 0 ||
305 strcasecmp(msg->return_path, md1) == 0 ||
306 strncasecmp(msg->return_path, md2, strlen(md2)) == 0)
309 bounce_to = (run.bouncemail ? msg->return_path : run.postmaster);
311 SMTP_setmode(SMTP_MODE);
313 /* can't just use fetchmailhost here, it might be localhost */
314 if (fqdn_of_host == NULL)
315 fqdn_of_host = host_fqdn();
316 strcat(daemon_name, fqdn_of_host);
318 /* we need only SMTP for this purpose */
319 if ((sock = SockOpen("localhost", SMTP_PORT, NULL, NULL)) == -1)
322 if (SMTP_ok(sock) != SM_OK)
328 if (SMTP_helo(sock, fetchmailhost) != SM_OK
329 || SMTP_from(sock, daemon_name, (char *)NULL) != SM_OK
330 || SMTP_rcpt(sock, bounce_to) != SM_OK
331 || SMTP_data(sock) != SM_OK)
338 /* our first duty is to keep the sacred foo counters turning... */
340 snprintf(boundary, sizeof(boundary),
343 #endif /* HAVE_SNPRINTF */
344 "foo-mani-padme-hum-%d-%d-%ld",
345 (int)getpid(), (int)getppid(), time((time_t *)NULL));
347 if (outlevel >= O_VERBOSE)
348 report(stdout, GT_("SMTP: (bounce-message body)\n"));
350 /* this will usually go to sylog... */
351 report(stderr, GT_("mail from %s bounced to %s\n"),
352 daemon_name, bounce_to);
354 /* bouncemail headers */
355 SockPrintf(sock, "Return-Path: <>\r\n");
356 SockPrintf(sock, "From: %s\r\n", daemon_name);
357 SockPrintf(sock, "To: %s\r\n", bounce_to);
358 SockPrintf(sock, "MIME-Version: 1.0\r\n");
359 SockPrintf(sock, "Content-Type: multipart/report; report-type=delivery-status;\r\n\tboundary=\"%s\"\r\n", boundary);
360 SockPrintf(sock, "\r\n");
362 /* RFC1892 part 1 -- human-readable message */
363 SockPrintf(sock, "--%s\r\n", boundary);
364 SockPrintf(sock,"Content-Type: text/plain\r\n");
365 SockPrintf(sock, "\r\n");
366 SockWrite(sock, message, strlen(message));
367 SockPrintf(sock, "\r\n");
368 SockPrintf(sock, "\r\n");
375 /* RFC1892 part 2 -- machine-readable responses */
376 SockPrintf(sock, "--%s\r\n", boundary);
377 SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
378 SockPrintf(sock, "\r\n");
379 SockPrintf(sock, "Reporting-MTA: dns; %s\r\n", fetchmailhost);
382 for (idp = msg->recipients; idp; idp = idp->next)
383 if (idp->val.status.mark == userclass)
386 /* Minimum RFC1894 compliance + Diagnostic-Code field */
387 SockPrintf(sock, "\r\n");
388 SockPrintf(sock, "Final-Recipient: rfc822; %s\r\n",
389 rcpt_address (ctl, idp->id, 1));
390 SockPrintf(sock, "Last-Attempt-Date: %s\r\n", rfc822timestamp());
391 SockPrintf(sock, "Action: failed\r\n");
394 /* one error applies to all users */
396 else if (nerrors <= nusers)
398 SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
402 /* errors correspond 1-1 to selected users */
403 error = errors[nusers++];
405 if (strlen(error) > 9 && isdigit(error[4])
406 && error[5] == '.' && isdigit(error[6])
407 && error[7] == '.' && isdigit(error[8]))
408 /* Enhanced status code available, use it */
409 SockPrintf(sock, "Status: %5.5s\r\n", &(error[4]));
411 /* Enhanced status code not available, fake one */
412 SockPrintf(sock, "Status: %c.0.0\r\n", error[0]);
413 SockPrintf(sock, "Diagnostic-Code: %s\r\n", error);
415 SockPrintf(sock, "\r\n");
418 /* RFC1892 part 3 -- headers of undelivered message */
419 SockPrintf(sock, "--%s\r\n", boundary);
420 SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
421 SockPrintf(sock, "\r\n");
424 SockWrite(sock, msg->headers, strlen(msg->headers));
425 SockPrintf(sock, "\r\n");
427 SockPrintf(sock, "--%s--\r\n", boundary);
429 if (SMTP_eom(sock) != SM_OK || SMTP_quit(sock))
440 static int handle_smtp_report(struct query *ctl, struct msgblk *msg)
441 /* handle SMTP errors based on the content of SMTP_response */
442 /* return of PS_REFUSED deletes mail from the server; PS_TRANSIENT keeps it */
444 int smtperr = atoi(smtp_response);
449 xalloca(responses[0], char *, strlen(smtp_response)+1);
450 strcpy(responses[0], smtp_response);
454 * Don't do this! It can really mess you up if, for example, you're
455 * reporting an error with a single RCPT TO address among several;
456 * RSET discards the message body and it doesn't get sent to the
459 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
460 if (outlevel >= O_DEBUG)
461 report(stdout, GT_("Saved error is still %d\n"), smtperr);
462 #endif /* __UNUSED */
465 * Note: send_bouncemail message strings are not made subject
466 * to gettext translation because (a) they're going to be
467 * embedded in a text/plain 7bit part, and (b) they're
468 * going to be associated with listener error-response
469 * messages, which are probably in English (none of the
470 * MTAs I know about are internationalized).
472 for( walk = ctl->antispam; walk; walk = walk->next )
473 if ( walk->val.status.num == smtperr )
479 /* if (str_find(&ctl->antispam, smtperr)) */
483 * SMTP listener explicitly refuses to deliver mail
484 * coming from this address, probably due to an
485 * anti-spam domain exclusion. Respect this. Don't
486 * try to ship the message, and don't prevent it from
487 * being deleted. There's no point in bouncing the
488 * email either since most spammers don't put their
489 * real return email address anywhere in the headers
490 * (unless the user insists with the SET SPAMBOUNCE
495 * 571 = sendmail's "unsolicited email refused"
496 * 550 = exim's new antispam response (temporary)
497 * 501 = exim's old antispam response
498 * 554 = Postfix antispam response.
505 snprintf(rejmsg, sizeof(rejmsg),
508 #endif /* HAVE_SNPRINTF */
509 "spam filter or virus scanner rejected message because:\r\n"
510 "%s\r\n", responses[0]);
512 send_bouncemail(ctl, msg, XMIT_ACCEPT,
513 rejmsg, 1, responses);
519 * Suppress error message only if the response specifically
520 * meant `excluded for policy reasons'. We *should* see
521 * an error when the return code is less specific.
524 report(stderr, GT_("%cMTP error: %s\n"),
530 case 552: /* message exceeds fixed maximum message size */
532 * Permanent no-go condition on the
533 * ESMTP server. Don't try to ship the message,
534 * and allow it to be deleted.
537 send_bouncemail(ctl, msg, XMIT_ACCEPT,
538 "This message was too large (SMTP error 552).\r\n",
542 case 553: /* invalid sending domain */
544 * These latter days 553 usually means a spammer is trying to
545 * cover his tracks. We never bouncemail on these, because
546 * (a) the return address is invalid by definition, and
547 * (b) we wouldn't want spammers to get confirmation that
548 * this address is live, anyway.
550 #ifdef __DONT_FEED_THE_SPAMMERS__
552 send_bouncemail(ctl, msg, XMIT_ACCEPT,
553 "Invalid address in MAIL FROM (SMTP error 553).\r\n",
555 #endif /* __DONT_FEED_THE_SPAMMERS__ */
559 /* bounce non-transient errors back to the sender */
560 if (smtperr >= 500 && smtperr <= 599)
562 send_bouncemail(ctl, msg, XMIT_ACCEPT,
563 "General SMTP/ESMTP error.\r\n",
568 * We're going to end up here on 4xx errors, like:
570 * 451: temporarily unable to identify sender (exim)
571 * 452: temporary out-of-queue-space condition on the ESMTP server.
573 * These are temporary errors. Don't try to ship the message,
574 * and suppress deletion so it can be retried on a future
577 * Bouncemail *might* be appropriate here as a delay
578 * notification (note; if we ever add this, we must make
579 * sure the RFC1894 Action field is "delayed" rather than
580 * "failed"). But it's not really necessary because
581 * these are not actual failures, we're very likely to be
582 * able to recover on the next cycle.
584 return(PS_TRANSIENT);
588 static int handle_smtp_report_without_bounce(struct query *ctl, struct msgblk *msg)
589 /* handle SMTP errors based on the content of SMTP_response */
590 /* atleast one PS_TRANSIENT: do not send the bounce mail, keep the mail;
591 * no PS_TRANSIENT, atleast one PS_SUCCESS: send the bounce mail, delete the mail;
592 * no PS_TRANSIENT, no PS_SUCCESS: do not send the bounce mail, delete the mail */
594 int smtperr = atoi(smtp_response);
596 if (str_find(&ctl->antispam, smtperr))
604 report(stderr, GT_("%cMTP error: %s\n"),
610 case 552: /* message exceeds fixed maximum message size */
615 case 553: /* invalid sending domain */
616 #ifdef __DONT_FEED_THE_SPAMMERS__
619 #endif /* __DONT_FEED_THE_SPAMMERS__ */
623 /* bounce non-transient errors back to the sender */
624 if (smtperr >= 500 && smtperr <= 599)
626 return(PS_TRANSIENT);
630 /* these are shared by open_sink and stuffline */
633 int stuffline(struct query *ctl, char *buf)
634 /* ship a line to the given control block's output sink (SMTP server or MDA) */
639 /* The line may contain NUL characters. Find the last char to use
640 * -- the real line termination is the sequence "\n\0".
642 last = buf + 1; /* last[-1] must be valid! */
643 while ((last += strlen(last)) && (last[-1] != '\n'))
646 /* fix message lines that have only \n termination (for qmail) */
649 if (last - 1 == buf || last[-2] != '\r')
658 phase = FORWARDING_WAIT;
661 * SMTP byte-stuffing. We only do this if the protocol does *not*
662 * use .<CR><LF> as EOM. If it does, the server will already have
663 * decorated any . lines it sends back up.
667 if (ctl->server.base_protocol->delimited) /* server has already byte-stuffed */
672 /* writing to SMTP, leave the byte-stuffing in place */;
674 else /* if (!protocol->delimited) -- not byte-stuffed already */
676 if (!ctl->mda) /* byte-stuff it */
679 SockWrite(ctl->smtp_socket, buf, 1);
682 fwrite(buf, 1, 1, sinkfp);
688 /* we may need to strip carriage returns */
693 for (sp = tp = buf; sp < last; sp++)
701 if (ctl->mda || ctl->bsmtp)
702 n = fwrite(buf, last - buf, 1, sinkfp);
703 else if (ctl->smtp_socket != -1)
704 n = SockWrite(ctl->smtp_socket, buf, last - buf);
711 static int open_bsmtp_sink(struct query *ctl, struct msgblk *msg,
712 int *good_addresses, int *bad_addresses)
713 /* open a BSMTP stream */
717 if (strcmp(ctl->bsmtp, "-") == 0)
720 sinkfp = fopen(ctl->bsmtp, "a");
722 /* see the ap computation under the SMTP branch */
724 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
726 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
727 fputs(" BODY=8BITMIME", sinkfp);
728 else if (ctl->mimemsg & MSG_IS_7BIT)
729 fputs(" BODY=7BIT", sinkfp);
731 /* exim's BSMTP processor does not handle SIZE */
732 /* fprintf(sinkfp, " SIZE=%d", msg->reallen); */
734 fprintf(sinkfp, "\r\n");
737 * RFC 1123 requires that the domain name part of the
738 * RCPT TO address be "canonicalized", that is a FQDN
739 * or MX but not a CNAME. Some listeners (like exim)
740 * enforce this. Now that we have the actual hostname,
741 * compute what we should canonicalize with.
743 ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
746 for (idp = msg->recipients; idp; idp = idp->next)
747 if (idp->val.status.mark == XMIT_ACCEPT)
749 fprintf(sinkfp, "RCPT TO: %s\r\n",
750 rcpt_address (ctl, idp->id, 1));
754 fputs("DATA\r\n", sinkfp);
758 report(stderr, GT_("BSMTP file open or preamble write failed\n"));
765 /* this is experimental and will be removed if double bounces are reported */
766 #define EXPLICIT_BOUNCE_ON_BAD_ADDRESS
769 static const char *is_quad(const char *q)
770 /* Check if the string passed in points to what could be one quad of a
771 * dotted-quad IP address. Requirements are that the string is not a
772 * NULL pointer, begins with a period (which is skipped) or a digit
773 * and ends with a period or a NULL. If these requirements are met, a
774 * pointer to the last character (the period or the NULL character) is
775 * returned; otherwise NULL.
784 for(r=q;isdigit(*r);r++)
786 if ( ((*r) && (*r != '.')) || ((r-q) < 1) || ((r-q)>3) )
788 /* Make sure quad is < 255 */
797 else if (*(q+1) == '5')
807 static int is_dottedquad(const char *hostname)
808 /* Returns a true value if the passed in string looks like an IP
809 * address in dotted-quad form, and a false value otherwise.
813 return ((hostname=is_quad(is_quad(is_quad(is_quad(hostname))))) != NULL) &&
817 static int open_smtp_sink(struct query *ctl, struct msgblk *msg,
818 int *good_addresses, int *bad_addresses)
819 /* open an SMTP stream */
823 char options[MSGBUFSIZE];
824 char addr[HOSTLEN+USERNAMELEN+1];
825 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
826 char **from_responses;
827 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
829 int force_transient_error = 0;
833 * Compute ESMTP options.
836 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
837 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
838 strcpy(options, " BODY=8BITMIME");
839 else if (ctl->mimemsg & MSG_IS_7BIT)
840 strcpy(options, " BODY=7BIT");
843 if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
844 sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
847 * Try to get the SMTP listener to take the Return-Path
848 * address as MAIL FROM. If it won't, fall back on the
849 * remotename and mailserver host. This won't affect replies,
850 * which use the header From address anyway; the MAIL FROM
851 * address is a place for the SMTP listener to send
852 * bouncemail. The point is to guarantee a FQDN in the MAIL
853 * FROM line -- some SMTP listeners, like smail, become
856 * RFC 1123 requires that the domain name part of the
857 * MAIL FROM address be "canonicalized", that is a
858 * FQDN or MX but not a CNAME. We'll assume the Return-Path
859 * header is already in this form here (it certainly
860 * is if rewrite is on). RFC 1123 is silent on whether
861 * a nonexistent hostname part is considered canonical.
863 * This is a potential problem if the MTAs further upstream
864 * didn't pass canonicalized From/Return-Path lines, *and* the
865 * local SMTP listener insists on them.
867 * Handle the case where an upstream MTA is setting a return
868 * path equal to "@". Ghod knows why anyone does this, but
869 * it's been reported to happen in mail from Amazon.com and
872 * Also, if the hostname is a dotted quad, wrap it in square brackets.
873 * Apparently this is required by RFC2821, section 4.1.3.
875 if (!msg->return_path[0] || (msg->return_path[0] == '@'))
877 if (is_dottedquad(ctl->server.truename))
880 snprintf(addr, sizeof(addr),
883 #endif /* HAVE_SNPRINTF */
884 "%s@[%s]", ctl->remotename, ctl->server.truename);
889 snprintf(addr, sizeof(addr),
892 #endif /* HAVE_SNPRINTF */
893 "%s@%s", ctl->remotename, ctl->server.truename);
897 else if (strchr(msg->return_path,'@') || strchr(msg->return_path,'!'))
898 ap = msg->return_path;
899 /* in case Return-Path was "<>" we want to preserve that */
900 else if (strcmp(msg->return_path,"<>") == 0)
901 ap = msg->return_path;
902 else /* in case Return-Path existed but was local */
904 if (is_dottedquad(ctl->server.truename))
907 snprintf(addr, sizeof(addr),
910 #endif /* HAVE_SNPRINTF */
911 "%s@[%s]", msg->return_path, ctl->server.truename);
916 snprintf(addr, sizeof(addr),
919 #endif /* HAVE_SNPRINTF */
920 "%s@%s", msg->return_path, ctl->server.truename);
925 if ((smtp_err = SMTP_from(ctl->smtp_socket, ap, options)) == SM_UNRECOVERABLE)
928 return(PS_TRANSIENT);
930 if (smtp_err != SM_OK)
932 int err = handle_smtp_report(ctl, msg);
934 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
939 * Now list the recipient addressees
942 for (idp = msg->recipients; idp; idp = idp->next)
944 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
945 xalloca(from_responses, char **, sizeof(char *) * total_addresses);
946 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
947 for (idp = msg->recipients; idp; idp = idp->next)
948 if (idp->val.status.mark == XMIT_ACCEPT)
951 address = rcpt_address (ctl, idp->id, 1);
952 if ((smtp_err = SMTP_rcpt(ctl->smtp_socket, address)) == SM_UNRECOVERABLE)
955 return(PS_TRANSIENT);
957 if (smtp_err == SM_OK)
961 switch (handle_smtp_report_without_bounce(ctl, msg))
964 force_transient_error = 1;
968 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
969 xalloca(from_responses[*bad_addresses],
971 strlen(smtp_response)+1);
972 strcpy(from_responses[*bad_addresses], smtp_response);
973 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
976 idp->val.status.mark = XMIT_RCPTBAD;
977 if (outlevel >= O_VERBOSE)
979 GT_("%cMTP listener doesn't like recipient address `%s'\n"),
980 ctl->listener, address);
984 if (outlevel >= O_VERBOSE)
986 GT_("%cMTP listener doesn't really like recipient address `%s'\n"),
987 ctl->listener, address);
993 if (force_transient_error) {
994 /* do not risk dataloss due to overengineered multidrop
995 * crap. If one of the recipients returned PS_TRANSIENT,
996 * we return exactly that.
998 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
999 return(PS_TRANSIENT);
1001 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
1003 * This should not be necessary, because the SMTP listener itself
1004 * should genrate a bounce for the bad address.
1007 send_bouncemail(ctl, msg, XMIT_RCPTBAD,
1008 "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
1009 *bad_addresses, from_responses);
1010 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
1013 * It's tempting to do local notification only if bouncemail was
1014 * insufficient -- that is, to add && total_addresses > *bad_addresses
1015 * to the test here. The problem with this theory is that it would
1016 * make initial diagnosis of a broken multidrop configuration very
1017 * hard -- most single-recipient messages would just invisibly bounce.
1019 if (!(*good_addresses))
1021 if (!run.postmaster[0])
1023 if (outlevel >= O_VERBOSE)
1024 report(stderr, GT_("no address matches; no postmaster set.\n"));
1025 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1028 if ((smtp_err = SMTP_rcpt(ctl->smtp_socket,
1029 rcpt_address (ctl, run.postmaster, 0))) == SM_UNRECOVERABLE)
1032 return(PS_TRANSIENT);
1034 if (smtp_err != SM_OK)
1036 report(stderr, GT_("can't even send to %s!\n"), run.postmaster);
1037 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1041 if (outlevel >= O_VERBOSE)
1042 report(stderr, GT_("no address matches; forwarding to %s.\n"), run.postmaster);
1046 * Tell the listener we're ready to send data.
1047 * Some listeners (like zmailer) may return antispam errors here.
1049 if ((smtp_err = SMTP_data(ctl->smtp_socket)) == SM_UNRECOVERABLE)
1052 return(PS_TRANSIENT);
1054 if (smtp_err != SM_OK)
1056 int err = handle_smtp_report(ctl, msg);
1057 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1062 * We need to stash this away in order to know how many
1063 * response lines to expect after the LMTP end-of-message.
1065 lmtp_responses = *good_addresses;
1070 static int open_mda_sink(struct query *ctl, struct msgblk *msg,
1071 int *good_addresses, int *bad_addresses)
1072 /* open a stream to a local MDA */
1076 #endif /* HAVE_SETEUID */
1078 int length = 0, fromlen = 0, nameslen = 0;
1079 char *names = NULL, *before, *after, *from = NULL;
1081 ctl->destaddr = "localhost";
1083 for (idp = msg->recipients; idp; idp = idp->next)
1084 if (idp->val.status.mark == XMIT_ACCEPT)
1085 (*good_addresses)++;
1087 length = strlen(ctl->mda);
1088 before = xstrdup(ctl->mda);
1090 /* get user addresses for %T (or %s for backward compatibility) */
1091 if (strstr(before, "%s") || strstr(before, "%T"))
1094 * We go through this in order to be able to handle very
1095 * long lists of users and (re)implement %s.
1098 for (idp = msg->recipients; idp; idp = idp->next)
1099 if ((idp->val.status.mark == XMIT_ACCEPT))
1100 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1101 if ((*good_addresses == 0))
1102 nameslen = strlen(run.postmaster);
1104 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1105 if (*good_addresses == 0)
1106 strcpy(names, run.postmaster);
1110 for (idp = msg->recipients; idp; idp = idp->next)
1111 if (idp->val.status.mark == XMIT_ACCEPT)
1113 strcat(names, idp->id);
1116 names[--nameslen] = '\0'; /* chop trailing space */
1122 /* get From address for %F */
1123 if (strstr(before, "%F"))
1125 from = xstrdup(msg->return_path);
1129 fromlen = strlen(from);
1132 /* do we have to build an mda string? */
1137 /* find length of resulting mda string */
1139 while ((sp = strstr(sp, "%s"))) {
1140 length += nameslen; /* subtract %s and add '' */
1144 while ((sp = strstr(sp, "%T"))) {
1145 length += nameslen; /* subtract %T and add '' */
1149 while ((sp = strstr(sp, "%F"))) {
1150 length += fromlen; /* subtract %F and add '' */
1154 after = xmalloc(length + 1);
1156 /* copy mda source string to after, while expanding %[sTF] */
1157 for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
1158 if (sp[0] != '%') continue;
1160 /* need to expand? BTW, no here overflow, because in
1161 ** the worst case (end of string) sp[1] == '\0' */
1162 if (sp[1] == 's' || sp[1] == 'T') {
1167 sp++; /* position sp over [sT] */
1168 dp--; /* adjust dp */
1169 } else if (sp[1] == 'F') {
1174 sp++; /* position sp over F */
1175 dp--; /* adjust dp */
1194 if (outlevel >= O_DEBUG)
1195 report(stdout, GT_("about to deliver with: %s\n"), before);
1199 * Arrange to run with user's permissions if we're root.
1200 * This will initialize the ownership of any files the
1201 * MDA creates properly. (The seteuid call is available
1202 * under all BSDs and Linux)
1204 orig_uid = getuid();
1206 #endif /* HAVE_SETEUID */
1208 sinkfp = popen(before, "w");
1213 /* this will fail quietly if we didn't start as root */
1215 #endif /* HAVE_SETEUID */
1219 report(stderr, GT_("MDA open failed\n"));
1224 * We need to disable the normal SIGCHLD handling here because
1225 * sigchld_handler() would reap away the error status, returning
1226 * error status instead of 0 for successful completion.
1228 set_signal_handler(SIGCHLD, SIG_DFL);
1233 int open_sink(struct query *ctl, struct msgblk *msg,
1234 int *good_addresses, int *bad_addresses)
1235 /* set up sinkfp to be an input sink we can ship a message to */
1237 *bad_addresses = *good_addresses = 0;
1239 if (ctl->bsmtp) /* dump to a BSMTP batch file */
1240 return(open_bsmtp_sink(ctl, msg, good_addresses, bad_addresses));
1242 * Try to forward to an SMTP or LMTP listener. If the attempt to
1243 * open a socket fails, fall through to attempt delivery via
1246 else if (!ctl->mda && smtp_open(ctl) != -1)
1247 return(open_smtp_sink(ctl, msg, good_addresses, bad_addresses));
1250 * Awkward case. User didn't specify an MDA. Our attempt to get a
1251 * listener socket failed. Try to cope anyway -- initial configuration
1252 * may have found procmail.
1256 report(stderr, GT_("%cMTP connect to %s failed\n"),
1258 ctl->smtphost ? ctl->smtphost : "localhost");
1260 #ifndef FALLBACK_MDA
1261 /* No fallback MDA declared. Bail out. */
1265 * If user had things set up to forward offsite, no way
1266 * we want to deliver locally!
1268 if (ctl->smtphost && strcmp(ctl->smtphost, "localhost"))
1272 * User was delivering locally. We have a fallback MDA.
1273 * Latch it in place, logging the error, and fall through.
1274 * Set stripcr as we would if MDA had been the initial transport
1276 ctl->mda = FALLBACK_MDA;
1278 ctl->stripcr = TRUE;
1280 report(stderr, GT_("can't raise the listener; falling back to %s"),
1285 if (ctl->mda) /* must deliver through an MDA */
1286 return(open_mda_sink(ctl, msg, good_addresses, bad_addresses));
1291 void release_sink(struct query *ctl)
1292 /* release the per-message output sink, whether it's a pipe or SMTP socket */
1294 if (ctl->bsmtp && sinkfp)
1296 if (strcmp(ctl->bsmtp, "-"))
1299 sinkfp = (FILE *)NULL;
1307 sinkfp = (FILE *)NULL;
1309 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1313 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
1314 /* perform end-of-message actions on the current output sink */
1321 /* close the delivery pipe, we'll reopen before next message */
1324 rc = pclose(sinkfp);
1325 sinkfp = (FILE *)NULL;
1330 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1334 if (WIFSIGNALED(rc)) {
1336 GT_("MDA died of signal %d\n"), WTERMSIG(rc));
1337 } else if (WIFEXITED(rc)) {
1339 GT_("MDA returned nonzero status %d\n"), WEXITSTATUS(rc));
1342 GT_("Strange: MDA pclose returned %d, cannot handle at %s:%d\n"), rc, __FILE__, __LINE__);
1348 else if (ctl->bsmtp && sinkfp)
1352 /* implicit disk-full check here... */
1353 fputs(".\r\n", sinkfp);
1354 error = ferror(sinkfp);
1355 if (strcmp(ctl->bsmtp, "-"))
1357 if (fclose(sinkfp) == EOF) error = 1;
1358 sinkfp = (FILE *)NULL;
1363 GT_("Message termination or close of BSMTP file failed\n"));
1369 /* write message terminator */
1370 if ((smtp_err = SMTP_eom(ctl->smtp_socket)) == SM_UNRECOVERABLE)
1375 if (smtp_err != SM_OK)
1377 if (handle_smtp_report(ctl, msg) != PS_REFUSED)
1379 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1384 report(stderr, GT_("SMTP listener refused delivery\n"));
1385 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1391 * If this is an SMTP connection, SMTP_eom() ate the response.
1392 * But could be this is an LMTP connection, in which case we have to
1393 * interpret either (a) a single 503 response meaning there
1394 * were no successful RCPT TOs, or (b) a variable number of
1395 * responses, one for each successful RCPT TO. We need to send
1396 * bouncemail on each failed response and then return TRUE anyway,
1397 * otherwise the message will get left in the queue and resent
1398 * to people who got it the first time.
1400 if (ctl->listener == LMTP_MODE)
1402 if (lmtp_responses == 0)
1404 SMTP_ok(ctl->smtp_socket);
1407 * According to RFC2033, 503 is the only legal response
1408 * if no RCPT TO commands succeeded. No error recovery
1409 * is really possible here, as we have no idea what
1410 * insane thing the listener might be doing if it doesn't
1413 if (atoi(smtp_response) == 503)
1414 report(stderr, GT_("LMTP delivery error on EOM\n"));
1417 GT_("Unexpected non-503 response to LMTP EOM: %s\n"),
1421 * It's not completely clear what to do here. We choose to
1422 * interpret delivery failure here as a transient error,
1423 * the same way SMTP delivery failure is handled. If we're
1424 * wrong, an undead message will get stuck in the queue.
1433 /* eat the RFC2033-required responses, saving errors */
1434 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
1435 for (errors = i = 0; i < lmtp_responses; i++)
1437 if ((smtp_err = SMTP_ok(ctl->smtp_socket)) == SM_UNRECOVERABLE)
1442 if (smtp_err == SM_OK)
1443 responses[i] = (char *)NULL;
1446 xalloca(responses[errors],
1448 strlen(smtp_response)+1);
1449 strcpy(responses[errors], smtp_response);
1455 return(TRUE); /* all deliveries succeeded */
1458 * One or more deliveries failed.
1459 * If we can bounce a failures list back to the
1460 * sender, and the postmaster does not want to
1461 * deal with the bounces return TRUE, deleting the
1462 * message from the server so it won't be
1463 * re-forwarded on subsequent poll cycles.
1465 return(send_bouncemail(ctl, msg, XMIT_ACCEPT,
1466 "LSMTP partial delivery failure.\r\n",
1467 errors, responses));
1475 int open_warning_by_mail(struct query *ctl, struct msgblk *msg)
1476 /* set up output sink for a mailed warning to calling user */
1481 * Dispatching warning email is a little complicated. The problem is
1482 * that we have to deal with three distinct cases:
1484 * 1. Single-drop running from user account. Warning mail should
1485 * go to the local name for which we're collecting (coincides
1486 * with calling user).
1488 * 2. Single-drop running from root or other privileged ID, with rc
1489 * file generated on the fly (Ken Estes's weird setup...) Mail
1490 * should go to the local name for which we're collecting (does not
1491 * coincide with calling user).
1493 * 3. Multidrop. Mail must go to postmaster. We leave the recipients
1494 * member null so this message will fall through to run.postmaster.
1496 * The zero in the reallen element means we won't pass a SIZE
1497 * option to ESMTP; the message length would be more trouble than
1498 * it's worth to compute.
1500 struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON@", 0};
1503 strcat(reply.return_path, ctl->smtpaddress ? ctl->smtpaddress :
1506 if (!MULTIDROP(ctl)) /* send to calling user */
1508 save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
1509 status = open_sink(ctl, &reply, &good, &bad);
1510 free_str_list(&reply.recipients);
1512 else /* send to postmaster */
1513 status = open_sink(ctl, &reply, &good, &bad);
1514 if (status == 0) stuff_warning(ctl, "Date: %s", rfc822timestamp());
1518 #if defined(HAVE_STDARG_H)
1519 void stuff_warning(struct query *ctl, const char *fmt, ... )
1521 void stuff_warning(struct query *ctl, fmt, va_alist)
1523 const char *fmt; /* printf-style format */
1526 /* format and ship a warning message line by mail */
1528 /* make huge -- i18n can bulk up error messages a lot */
1529 char buf[2*MSGBUFSIZE+4];
1533 * stuffline() requires its input to be writeable (for CR stripping),
1534 * so we needed to copy the message to a writeable buffer anyway in
1535 * case it was a string constant. We make a virtue of that necessity
1536 * here by supporting stdargs/varargs.
1538 #if defined(HAVE_STDARG_H)
1543 #ifdef HAVE_VSNPRINTF
1544 vsnprintf(buf, sizeof(buf), fmt, ap);
1546 vsprintf(buf, fmt, ap);
1550 #ifdef HAVE_SNPRINTF
1551 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1553 strcat(buf, "\r\n");
1554 #endif /* HAVE_SNPRINTF */
1556 /* guard against very long lines */
1557 buf[MSGBUFSIZE+1] = '\r';
1558 buf[MSGBUFSIZE+2] = '\n';
1559 buf[MSGBUFSIZE+3] = '\0';
1561 stuffline(ctl, buf);
1564 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
1565 /* sign and send mailed warnings */
1567 stuff_warning(ctl, GT_("--\n\t\t\t\tThe Fetchmail Daemon\n"));
1568 close_sink(ctl, msg, TRUE);
1571 /* sink.c ends here */