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)
218 /* replace unsafe shellchars by an _ */
220 const static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
223 for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
227 char *rcpt_address(struct query *ctl, const char *id,
230 static char addr[HOSTLEN+USERNAMELEN+1];
234 snprintf(addr, sizeof (addr), "%s", id);
236 sprintf(addr, "%s", id);
237 #endif /* HAVE_SNPRINTF */
239 else if (usesmtpname && ctl->smtpname)
242 snprintf(addr, sizeof (addr), "%s", ctl->smtpname);
244 sprintf(addr, "%s", ctl->smtpname);
245 #endif /* HAVE_SNPRINTF */
250 snprintf(addr, sizeof (addr), "%s@%s", id, ctl->destaddr);
252 sprintf(addr, "%s@%s", id, ctl->destaddr);
253 #endif /* HAVE_SNPRINTF */
258 static int send_bouncemail(struct query *ctl, struct msgblk *msg,
259 int userclass, char *message,
260 int nerrors, char *errors[])
261 /* bounce back an error report a la RFC 1892 */
263 char daemon_name[18 + HOSTLEN] = "FETCHMAIL-DAEMON@";
264 char boundary[BUFSIZ], *bounce_to;
266 static char *fqdn_of_host = NULL;
268 /* don't bounce in reply to undeliverable bounces */
269 if (!msg->return_path[0] || strcmp(msg->return_path, "<>") == 0)
272 bounce_to = (run.bouncemail ? msg->return_path : run.postmaster);
274 SMTP_setmode(SMTP_MODE);
276 /* can't just use fetchmailhost here, it might be localhost */
277 if (fqdn_of_host == NULL)
278 fqdn_of_host = host_fqdn();
279 strcat(daemon_name, fqdn_of_host);
281 /* we need only SMTP for this purpose */
282 if ((sock = SockOpen("localhost", SMTP_PORT, NULL, NULL)) == -1)
285 if (SMTP_ok(sock) != SM_OK)
291 if (SMTP_helo(sock, fetchmailhost) != SM_OK
292 || SMTP_from(sock, daemon_name, (char *)NULL) != SM_OK
293 || SMTP_rcpt(sock, bounce_to) != SM_OK
294 || SMTP_data(sock) != SM_OK)
301 /* our first duty is to keep the sacred foo counters turning... */
303 snprintf(boundary, sizeof(boundary),
306 #endif /* HAVE_SNPRINTF */
307 "foo-mani-padme-hum-%d-%d-%ld",
308 (int)getpid(), (int)getppid(), time((time_t *)NULL));
310 if (outlevel >= O_VERBOSE)
311 report(stdout, GT_("SMTP: (bounce-message body)\n"));
313 /* this will usually go to sylog... */
314 report(stderr, GT_("mail from %s bounced to %s\n"),
315 daemon_name, bounce_to);
317 /* bouncemail headers */
318 SockPrintf(sock, "Return-Path: <>\r\n");
319 SockPrintf(sock, "From: %s\r\n", daemon_name);
320 SockPrintf(sock, "To: %s\r\n", bounce_to);
321 SockPrintf(sock, "MIME-Version: 1.0\r\n");
322 SockPrintf(sock, "Content-Type: multipart/report; report-type=delivery-status;\r\n\tboundary=\"%s\"\r\n", boundary);
323 SockPrintf(sock, "\r\n");
325 /* RFC1892 part 1 -- human-readable message */
326 SockPrintf(sock, "--%s\r\n", boundary);
327 SockPrintf(sock,"Content-Type: text/plain\r\n");
328 SockPrintf(sock, "\r\n");
329 SockWrite(sock, message, strlen(message));
330 SockPrintf(sock, "\r\n");
331 SockPrintf(sock, "\r\n");
338 /* RFC1892 part 2 -- machine-readable responses */
339 SockPrintf(sock, "--%s\r\n", boundary);
340 SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
341 SockPrintf(sock, "\r\n");
342 SockPrintf(sock, "Reporting-MTA: dns; %s\r\n", fetchmailhost);
345 for (idp = msg->recipients; idp; idp = idp->next)
346 if (idp->val.status.mark == userclass)
349 /* Minimum RFC1894 compliance + Diagnostic-Code field */
350 SockPrintf(sock, "\r\n");
351 SockPrintf(sock, "Final-Recipient: rfc822; %s\r\n",
352 rcpt_address (ctl, idp->id, 1));
353 SockPrintf(sock, "Last-Attempt-Date: %s\r\n", rfc822timestamp());
354 SockPrintf(sock, "Action: failed\r\n");
357 /* one error applies to all users */
359 else if (nerrors <= nusers)
361 SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
365 /* errors correspond 1-1 to selected users */
366 error = errors[nusers++];
368 if (strlen(error) > 9 && isdigit(error[4])
369 && error[5] == '.' && isdigit(error[6])
370 && error[7] == '.' && isdigit(error[8]))
371 /* Enhanced status code available, use it */
372 SockPrintf(sock, "Status: %5.5s\r\n", &(error[4]));
374 /* Enhanced status code not available, fake one */
375 SockPrintf(sock, "Status: %c.0.0\r\n", error[0]);
376 SockPrintf(sock, "Diagnostic-Code: %s\r\n", error);
378 SockPrintf(sock, "\r\n");
381 /* RFC1892 part 3 -- headers of undelivered message */
382 SockPrintf(sock, "--%s\r\n", boundary);
383 SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
384 SockPrintf(sock, "\r\n");
385 SockWrite(sock, msg->headers, strlen(msg->headers));
386 SockPrintf(sock, "\r\n");
387 SockPrintf(sock, "--%s--\r\n", boundary);
389 if (SMTP_eom(sock) != SM_OK || SMTP_quit(sock))
400 static int handle_smtp_report(struct query *ctl, struct msgblk *msg)
401 /* handle SMTP errors based on the content of SMTP_response */
402 /* return of PS_REFUSED deletes mail from the server; PS_TRANSIENT keeps it */
404 int smtperr = atoi(smtp_response);
407 xalloca(responses[0], char *, strlen(smtp_response)+1);
408 strcpy(responses[0], smtp_response);
412 * Don't do this! It can really mess you up if, for example, you're
413 * reporting an error with a single RCPT TO address among several;
414 * RSET discards the message body and it doesn't get sent to the
417 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
418 if (outlevel >= O_DEBUG)
419 report(stdout, GT_("Saved error is still %d\n"), smtperr);
420 #endif /* __UNUSED */
423 * Note: send_bouncemail message strings are not made subject
424 * to gettext translation because (a) they're going to be
425 * embedded in a text/plain 7bit part, and (b) they're
426 * going to be associated with listener error-response
427 * messages, which are probably in English (none of the
428 * MTAs I know about are internationalized).
430 if (str_find(&ctl->antispam, smtperr))
433 * SMTP listener explicitly refuses to deliver mail
434 * coming from this address, probably due to an
435 * anti-spam domain exclusion. Respect this. Don't
436 * try to ship the message, and don't prevent it from
437 * being deleted. There's no point in bouncing the
438 * email either since most spammers don't put their
439 * real return email address anywhere in the headers
440 * (unless the user insists with the SET SPAMBOUNCE
445 * 571 = sendmail's "unsolicited email refused"
446 * 550 = exim's new antispam response (temporary)
447 * 501 = exim's old antispam response
448 * 554 = Postfix antispam response.
455 snprintf(rejmsg, sizeof(rejmsg),
458 #endif /* HAVE_SNPRINTF */
459 "spam filter or virus scanner rejected message because:\r\n"
460 "%s\r\n", responses[0]);
462 send_bouncemail(ctl, msg, XMIT_ACCEPT,
463 rejmsg, 1, responses);
469 * Suppress error message only if the response specifically
470 * meant `excluded for policy reasons'. We *should* see
471 * an error when the return code is less specific.
474 report(stderr, GT_("%cMTP error: %s\n"),
480 case 552: /* message exceeds fixed maximum message size */
482 * Permanent no-go condition on the
483 * ESMTP server. Don't try to ship the message,
484 * and allow it to be deleted.
487 send_bouncemail(ctl, msg, XMIT_ACCEPT,
488 "This message was too large (SMTP error 552).\r\n",
492 case 553: /* invalid sending domain */
494 * These latter days 553 usually means a spammer is trying to
495 * cover his tracks. We never bouncemail on these, because
496 * (a) the return address is invalid by definition, and
497 * (b) we wouldn't want spammers to get confirmation that
498 * this address is live, anyway.
500 #ifdef __DONT_FEED_THE_SPAMMERS__
502 send_bouncemail(ctl, msg, XMIT_ACCEPT,
503 "Invalid address in MAIL FROM (SMTP error 553).\r\n",
505 #endif /* __DONT_FEED_THE_SPAMMERS__ */
509 /* bounce non-transient errors back to the sender */
510 if (smtperr >= 500 && smtperr <= 599)
511 if (send_bouncemail(ctl, msg, XMIT_ACCEPT,
512 "General SMTP/ESMTP error.\r\n",
514 return(run.bouncemail ? PS_REFUSED : PS_TRANSIENT);
516 * We're going to end up here on 4xx errors, like:
518 * 451: temporarily unable to identify sender (exim)
519 * 452: temporary out-of-queue-space condition on the ESMTP server.
521 * These are temporary errors. Don't try to ship the message,
522 * and suppress deletion so it can be retried on a future
525 * Bouncemail *might* be appropriate here as a delay
526 * notification (note; if we ever add this, we must make
527 * sure the RFC1894 Action field is "delayed" rather than
528 * "failed"). But it's not really necessary because
529 * these are not actual failures, we're very likely to be
530 * able to recover on the next cycle.
532 return(PS_TRANSIENT);
536 static int handle_smtp_report_without_bounce(struct query *ctl, struct msgblk *msg)
537 /* handle SMTP errors based on the content of SMTP_response */
538 /* atleast one PS_TRANSIENT: do not send the bounce mail, keep the mail;
539 * no PS_TRANSIENT, atleast one PS_SUCCESS: send the bounce mail, delete the mail;
540 * no PS_TRANSIENT, no PS_SUCCESS: do not send the bounce mail, delete the mail */
542 int smtperr = atoi(smtp_response);
544 if (str_find(&ctl->antispam, smtperr))
552 report(stderr, GT_("%cMTP error: %s\n"),
558 case 552: /* message exceeds fixed maximum message size */
563 case 553: /* invalid sending domain */
564 #ifdef __DONT_FEED_THE_SPAMMERS__
567 #endif /* __DONT_FEED_THE_SPAMMERS__ */
571 /* bounce non-transient errors back to the sender */
572 if (smtperr >= 500 && smtperr <= 599)
574 return(PS_TRANSIENT);
578 /* these are shared by open_sink and stuffline */
581 int stuffline(struct query *ctl, char *buf)
582 /* ship a line to the given control block's output sink (SMTP server or MDA) */
587 /* The line may contain NUL characters. Find the last char to use
588 * -- the real line termination is the sequence "\n\0".
590 last = buf + 1; /* last[-1] must be valid! */
591 while ((last += strlen(last)) && (last[-1] != '\n'))
594 /* fix message lines that have only \n termination (for qmail) */
597 if (last - 1 == buf || last[-2] != '\r')
606 phase = FORWARDING_WAIT;
609 * SMTP byte-stuffing. We only do this if the protocol does *not*
610 * use .<CR><LF> as EOM. If it does, the server will already have
611 * decorated any . lines it sends back up.
615 if (ctl->server.base_protocol->delimited) /* server has already byte-stuffed */
620 /* writing to SMTP, leave the byte-stuffing in place */;
622 else /* if (!protocol->delimited) -- not byte-stuffed already */
625 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
627 /* leave it alone */;
631 /* we may need to strip carriage returns */
636 for (sp = tp = buf; sp < last; sp++)
644 if (ctl->mda || ctl->bsmtp)
645 n = fwrite(buf, 1, last - buf, sinkfp);
646 else if (ctl->smtp_socket != -1)
647 n = SockWrite(ctl->smtp_socket, buf, last - buf);
654 static int open_bsmtp_sink(struct query *ctl, struct msgblk *msg,
655 int *good_addresses, int *bad_addresses)
656 /* open a BSMTP stream */
660 if (strcmp(ctl->bsmtp, "-") == 0)
663 sinkfp = fopen(ctl->bsmtp, "a");
665 /* see the ap computation under the SMTP branch */
667 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
669 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
670 fputs(" BODY=8BITMIME", sinkfp);
671 else if (ctl->mimemsg & MSG_IS_7BIT)
672 fputs(" BODY=7BIT", sinkfp);
674 /* exim's BSMTP processor does not handle SIZE */
675 /* fprintf(sinkfp, " SIZE=%d", msg->reallen); */
677 fprintf(sinkfp, "\r\n");
680 * RFC 1123 requires that the domain name part of the
681 * RCPT TO address be "canonicalized", that is a FQDN
682 * or MX but not a CNAME. Some listeners (like exim)
683 * enforce this. Now that we have the actual hostname,
684 * compute what we should canonicalize with.
686 ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
689 for (idp = msg->recipients; idp; idp = idp->next)
690 if (idp->val.status.mark == XMIT_ACCEPT)
692 fprintf(sinkfp, "RCPT TO: %s\r\n",
693 rcpt_address (ctl, idp->id, 1));
697 fputs("DATA\r\n", sinkfp);
701 report(stderr, GT_("BSMTP file open or preamble write failed\n"));
708 /* this is experimental and will be removed if double bounces are reported */
709 #define EXPLICIT_BOUNCE_ON_BAD_ADDRESS
712 static const char *is_quad(const char *q)
713 /* Check if the string passed in points to what could be one quad of a
714 * dotted-quad IP address. Requirements are that the string is not a
715 * NULL pointer, begins with a period (which is skipped) or a digit
716 * and ends with a period or a NULL. If these requirements are met, a
717 * pointer to the last character (the period or the NULL character) is
718 * returned; otherwise NULL.
727 for(r=q;isdigit(*r);r++)
729 if ( ((*r) && (*r != '.')) || ((r-q) < 1) || ((r-q)>3) )
731 /* Make sure quad is < 255 */
740 else if (*(q+1) == '5')
750 static int is_dottedquad(const char *hostname)
751 /* Returns a true value if the passed in string looks like an IP
752 * address in dotted-quad form, and a false value otherwise.
756 return ((hostname=is_quad(is_quad(is_quad(is_quad(hostname))))) != NULL) &&
760 static int open_smtp_sink(struct query *ctl, struct msgblk *msg,
761 int *good_addresses, int *bad_addresses)
762 /* open an SMTP stream */
766 char options[MSGBUFSIZE];
767 char addr[HOSTLEN+USERNAMELEN+1];
768 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
769 char **from_responses;
770 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
772 int force_transient_error = 0;
775 * Compute ESMTP options.
778 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
779 if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
780 strcpy(options, " BODY=8BITMIME");
781 else if (ctl->mimemsg & MSG_IS_7BIT)
782 strcpy(options, " BODY=7BIT");
785 if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
786 sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
789 * Try to get the SMTP listener to take the Return-Path
790 * address as MAIL FROM. If it won't, fall back on the
791 * remotename and mailserver host. This won't affect replies,
792 * which use the header From address anyway; the MAIL FROM
793 * address is a place for the SMTP listener to send
794 * bouncemail. The point is to guarantee a FQDN in the MAIL
795 * FROM line -- some SMTP listeners, like smail, become
798 * RFC 1123 requires that the domain name part of the
799 * MAIL FROM address be "canonicalized", that is a
800 * FQDN or MX but not a CNAME. We'll assume the Return-Path
801 * header is already in this form here (it certainly
802 * is if rewrite is on). RFC 1123 is silent on whether
803 * a nonexistent hostname part is considered canonical.
805 * This is a potential problem if the MTAs further upstream
806 * didn't pass canonicalized From/Return-Path lines, *and* the
807 * local SMTP listener insists on them.
809 * Handle the case where an upstream MTA is setting a return
810 * path equal to "@". Ghod knows why anyone does this, but
811 * it's been reported to happen in mail from Amazon.com and
814 * Also, if the hostname is a dotted quad, wrap it in square brackets.
815 * Apparently this is required by RFC2821, section 4.1.3.
817 if (!msg->return_path[0] || (msg->return_path[0] == '@'))
819 if (is_dottedquad(ctl->server.truename))
822 snprintf(addr, sizeof(addr),
825 #endif /* HAVE_SNPRINTF */
826 "%s@[%s]", ctl->remotename, ctl->server.truename);
831 snprintf(addr, sizeof(addr),
834 #endif /* HAVE_SNPRINTF */
835 "%s@%s", ctl->remotename, ctl->server.truename);
839 else if (strchr(msg->return_path,'@') || strchr(msg->return_path,'!'))
840 ap = msg->return_path;
841 else /* in case Return-Path existed but was local */
843 if (is_dottedquad(ctl->server.truename))
846 snprintf(addr, sizeof(addr),
849 #endif /* HAVE_SNPRINTF */
850 "%s@[%s]", msg->return_path, ctl->server.truename);
855 snprintf(addr, sizeof(addr),
858 #endif /* HAVE_SNPRINTF */
859 "%s@%s", msg->return_path, ctl->server.truename);
864 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
866 int err = handle_smtp_report(ctl, msg);
868 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
873 * Now list the recipient addressees
876 for (idp = msg->recipients; idp; idp = idp->next)
878 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
879 xalloca(from_responses, char **, sizeof(char *) * total_addresses);
880 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
881 for (idp = msg->recipients; idp; idp = idp->next)
882 if (idp->val.status.mark == XMIT_ACCEPT)
885 address = rcpt_address (ctl, idp->id, 1);
886 if (SMTP_rcpt(ctl->smtp_socket, address) == SM_OK)
890 switch (handle_smtp_report_without_bounce(ctl, msg))
893 force_transient_error = 1;
897 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
898 xalloca(from_responses[*bad_addresses],
900 strlen(smtp_response)+1);
901 strcpy(from_responses[*bad_addresses], smtp_response);
902 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
905 idp->val.status.mark = XMIT_RCPTBAD;
906 if (outlevel >= O_VERBOSE)
908 GT_("%cMTP listener doesn't like recipient address `%s'\n"),
909 ctl->listener, address);
913 if (outlevel >= O_VERBOSE)
915 GT_("%cMTP listener doesn't really like recipient address `%s'\n"),
916 ctl->listener, address);
922 if (force_transient_error) {
923 /* do not risk dataloss due to overengineered multidrop
924 * crap. If one of the recipients returned PS_TRANSIENT,
925 * we return exactly that.
927 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
928 return(PS_TRANSIENT);
930 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
932 * This should not be necessary, because the SMTP listener itself
933 * should genrate a bounce for the bad address.
936 send_bouncemail(ctl, msg, XMIT_RCPTBAD,
937 "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
938 *bad_addresses, from_responses);
939 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
942 * It's tempting to do local notification only if bouncemail was
943 * insufficient -- that is, to add && total_addresses > *bad_addresses
944 * to the test here. The problem with this theory is that it would
945 * make initial diagnosis of a broken multidrop configuration very
946 * hard -- most single-recipient messages would just invisibly bounce.
948 if (!(*good_addresses))
950 if (!run.postmaster[0])
952 if (outlevel >= O_VERBOSE)
953 report(stderr, GT_("no address matches; no postmaster set.\n"));
954 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
957 if (SMTP_rcpt(ctl->smtp_socket,
958 rcpt_address (ctl, run.postmaster, 0)) != SM_OK)
960 report(stderr, GT_("can't even send to %s!\n"), run.postmaster);
961 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
965 if (outlevel >= O_VERBOSE)
966 report(stderr, GT_("no address matches; forwarding to %s.\n"), run.postmaster);
970 * Tell the listener we're ready to send data.
971 * Some listeners (like zmailer) may return antispam errors here.
973 if (SMTP_data(ctl->smtp_socket) != SM_OK)
975 int err = handle_smtp_report(ctl, msg);
976 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
981 * We need to stash this away in order to know how many
982 * response lines to expect after the LMTP end-of-message.
984 lmtp_responses = *good_addresses;
989 static int open_mda_sink(struct query *ctl, struct msgblk *msg,
990 int *good_addresses, int *bad_addresses)
991 /* open a stream to a local MDA */
993 #ifdef HAVE_SIGACTION
994 struct sigaction sa_new;
995 #endif /* HAVE_SIGACTION */
998 #endif /* HAVE_SETEUID */
1000 int length = 0, fromlen = 0, nameslen = 0;
1001 char *names = NULL, *before, *after, *from = NULL;
1003 ctl->destaddr = "localhost";
1005 for (idp = msg->recipients; idp; idp = idp->next)
1006 if (idp->val.status.mark == XMIT_ACCEPT)
1007 (*good_addresses)++;
1009 length = strlen(ctl->mda);
1010 before = xstrdup(ctl->mda);
1012 /* get user addresses for %T (or %s for backward compatibility) */
1013 if (strstr(before, "%s") || strstr(before, "%T"))
1016 * We go through this in order to be able to handle very
1017 * long lists of users and (re)implement %s.
1020 for (idp = msg->recipients; idp; idp = idp->next)
1021 if ((idp->val.status.mark == XMIT_ACCEPT))
1022 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1023 if ((*good_addresses == 0))
1024 nameslen = strlen(run.postmaster);
1026 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1027 if (*good_addresses == 0)
1028 strcpy(names, run.postmaster);
1032 for (idp = msg->recipients; idp; idp = idp->next)
1033 if (idp->val.status.mark == XMIT_ACCEPT)
1035 strcat(names, idp->id);
1038 names[--nameslen] = '\0'; /* chop trailing space */
1041 /* sanitize names in order to contain only harmless shell chars */
1045 /* get From address for %F */
1046 if (strstr(before, "%F"))
1048 from = xstrdup(msg->return_path);
1050 /* sanitize from in order to contain *only* harmless shell chars */
1053 fromlen = strlen(from);
1056 /* do we have to build an mda string? */
1061 /* find length of resulting mda string */
1063 while ((sp = strstr(sp, "%s"))) {
1064 length += nameslen - 2; /* subtract %s */
1068 while ((sp = strstr(sp, "%T"))) {
1069 length += nameslen - 2; /* subtract %T */
1073 while ((sp = strstr(sp, "%F"))) {
1074 length += fromlen - 2; /* subtract %F */
1078 after = xmalloc(length + 1);
1080 /* copy mda source string to after, while expanding %[sTF] */
1081 for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
1082 if (sp[0] != '%') continue;
1084 /* need to expand? BTW, no here overflow, because in
1085 ** the worst case (end of string) sp[1] == '\0' */
1086 if (sp[1] == 's' || sp[1] == 'T') {
1089 sp++; /* position sp over [sT] */
1090 dp--; /* adjust dp */
1091 } else if (sp[1] == 'F') {
1094 sp++; /* position sp over F */
1095 dp--; /* adjust dp */
1114 if (outlevel >= O_DEBUG)
1115 report(stdout, GT_("about to deliver with: %s\n"), before);
1119 * Arrange to run with user's permissions if we're root.
1120 * This will initialize the ownership of any files the
1121 * MDA creates properly. (The seteuid call is available
1122 * under all BSDs and Linux)
1124 orig_uid = getuid();
1126 #endif /* HAVE_SETEUID */
1128 sinkfp = popen(before, "w");
1133 /* this will fail quietly if we didn't start as root */
1135 #endif /* HAVE_SETEUID */
1139 report(stderr, GT_("MDA open failed\n"));
1144 * We need to disable the normal SIGCHLD handling here because
1145 * sigchld_handler() would reap away the error status, returning
1146 * error status instead of 0 for successful completion.
1148 #ifndef HAVE_SIGACTION
1149 signal(SIGCHLD, SIG_DFL);
1151 memset (&sa_new, 0, sizeof sa_new);
1152 sigemptyset (&sa_new.sa_mask);
1153 sa_new.sa_handler = SIG_DFL;
1154 sigaction (SIGCHLD, &sa_new, NULL);
1155 #endif /* HAVE_SIGACTION */
1160 int open_sink(struct query *ctl, struct msgblk *msg,
1161 int *good_addresses, int *bad_addresses)
1162 /* set up sinkfp to be an input sink we can ship a message to */
1164 *bad_addresses = *good_addresses = 0;
1166 if (ctl->bsmtp) /* dump to a BSMTP batch file */
1167 return(open_bsmtp_sink(ctl, msg, good_addresses, bad_addresses));
1169 * Try to forward to an SMTP or LMTP listener. If the attempt to
1170 * open a socket fails, fall through to attempt delivery via
1173 else if (!ctl->mda && smtp_open(ctl) != -1)
1174 return(open_smtp_sink(ctl, msg, good_addresses, bad_addresses));
1177 * Awkward case. User didn't specify an MDA. Our attempt to get a
1178 * listener socket failed. Try to cope anyway -- initial configuration
1179 * may have found procmail.
1183 report(stderr, GT_("%cMTP connect to %s failed\n"),
1185 ctl->smtphost ? ctl->smtphost : "localhost");
1187 #ifndef FALLBACK_MDA
1188 /* No fallback MDA declared. Bail out. */
1192 * If user had things set up to forward offsite, no way
1193 * we want to deliver locally!
1195 if (ctl->smtphost && strcmp(ctl->smtphost, "localhost"))
1199 * User was delivering locally. We have a fallback MDA.
1200 * Latch it in place, logging the error, and fall through.
1201 * Set stripcr as we would if MDA had been the initial transport
1203 ctl->mda = FALLBACK_MDA;
1205 ctl->stripcr = TRUE;
1207 report(stderr, GT_("can't raise the listener; falling back to %s"),
1212 if (ctl->mda) /* must deliver through an MDA */
1213 return(open_mda_sink(ctl, msg, good_addresses, bad_addresses));
1218 void release_sink(struct query *ctl)
1219 /* release the per-message output sink, whether it's a pipe or SMTP socket */
1221 if (ctl->bsmtp && sinkfp)
1223 if (strcmp(ctl->bsmtp, "-"))
1226 sinkfp = (FILE *)NULL;
1234 sinkfp = (FILE *)NULL;
1236 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1240 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
1241 /* perform end-of-message actions on the current output sink */
1247 /* close the delivery pipe, we'll reopen before next message */
1250 rc = pclose(sinkfp);
1251 sinkfp = (FILE *)NULL;
1256 deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1260 if (WIFSIGNALED(rc)) {
1262 GT_("MDA died of signal %d\n"), WTERMSIG(rc));
1263 } else if (WIFEXITED(rc)) {
1265 GT_("MDA returned nonzero status %d\n"), WEXITSTATUS(rc));
1268 GT_("Strange: MDA pclose returned %d, cannot handle at %s:%d\n"), rc, __FILE__, __LINE__);
1274 else if (ctl->bsmtp && sinkfp)
1278 /* implicit disk-full check here... */
1279 fputs(".\r\n", sinkfp);
1280 error = ferror(sinkfp);
1281 if (strcmp(ctl->bsmtp, "-"))
1283 if (fclose(sinkfp) == EOF) error = 1;
1284 sinkfp = (FILE *)NULL;
1289 GT_("Message termination or close of BSMTP file failed\n"));
1295 /* write message terminator */
1296 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1298 if (handle_smtp_report(ctl, msg) != PS_REFUSED)
1300 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1305 report(stderr, GT_("SMTP listener refused delivery\n"));
1306 SMTP_rset(ctl->smtp_socket); /* stay on the safe side */
1312 * If this is an SMTP connection, SMTP_eom() ate the response.
1313 * But could be this is an LMTP connection, in which case we have to
1314 * interpret either (a) a single 503 response meaning there
1315 * were no successful RCPT TOs, or (b) a variable number of
1316 * responses, one for each successful RCPT TO. We need to send
1317 * bouncemail on each failed response and then return TRUE anyway,
1318 * otherwise the message will get left in the queue and resent
1319 * to people who got it the first time.
1321 if (ctl->listener == LMTP_MODE)
1323 if (lmtp_responses == 0)
1325 SMTP_ok(ctl->smtp_socket);
1328 * According to RFC2033, 503 is the only legal response
1329 * if no RCPT TO commands succeeded. No error recovery
1330 * is really possible here, as we have no idea what
1331 * insane thing the listener might be doing if it doesn't
1334 if (atoi(smtp_response) == 503)
1335 report(stderr, GT_("LMTP delivery error on EOM\n"));
1338 GT_("Unexpected non-503 response to LMTP EOM: %s\n"),
1342 * It's not completely clear what to do here. We choose to
1343 * interpret delivery failure here as a transient error,
1344 * the same way SMTP delivery failure is handled. If we're
1345 * wrong, an undead message will get stuck in the queue.
1354 /* eat the RFC2033-required responses, saving errors */
1355 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
1356 for (errors = i = 0; i < lmtp_responses; i++)
1358 if (SMTP_ok(ctl->smtp_socket) == SM_OK)
1359 responses[i] = (char *)NULL;
1362 xalloca(responses[errors],
1364 strlen(smtp_response)+1);
1365 strcpy(responses[errors], smtp_response);
1371 return(TRUE); /* all deliveries succeeded */
1374 * One or more deliveries failed.
1375 * If we can bounce a failures list back to the
1376 * sender, and the postmaster does not want to
1377 * deal with the bounces return TRUE, deleting the
1378 * message from the server so it won't be
1379 * re-forwarded on subsequent poll cycles.
1381 return(send_bouncemail(ctl, msg, XMIT_ACCEPT,
1382 "LSMTP partial delivery failure.\r\n",
1383 errors, responses));
1391 int open_warning_by_mail(struct query *ctl, struct msgblk *msg)
1392 /* set up output sink for a mailed warning to calling user */
1397 * Dispatching warning email is a little complicated. The problem is
1398 * that we have to deal with three distinct cases:
1400 * 1. Single-drop running from user account. Warning mail should
1401 * go to the local name for which we're collecting (coincides
1402 * with calling user).
1404 * 2. Single-drop running from root or other privileged ID, with rc
1405 * file generated on the fly (Ken Estes's weird setup...) Mail
1406 * should go to the local name for which we're collecting (does not
1407 * coincide with calling user).
1409 * 3. Multidrop. Mail must go to postmaster. We leave the recipients
1410 * member null so this message will fall through to run.postmaster.
1412 * The zero in the reallen element means we won't pass a SIZE
1413 * option to ESMTP; the message length would be more trouble than
1414 * it's worth to compute.
1416 struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON@", 0};
1419 strcat(reply.return_path, ctl->smtpaddress ? ctl->smtpaddress :
1422 if (!MULTIDROP(ctl)) /* send to calling user */
1424 save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
1425 status = open_sink(ctl, &reply, &good, &bad);
1426 free_str_list(&reply.recipients);
1428 else /* send to postmaster */
1429 status = open_sink(ctl, &reply, &good, &bad);
1430 stuff_warning(ctl, "Date: %s", rfc822timestamp());
1434 #if defined(HAVE_STDARG_H)
1435 void stuff_warning(struct query *ctl, const char *fmt, ... )
1437 void stuff_warning(struct query *ctl, fmt, va_alist)
1439 const char *fmt; /* printf-style format */
1442 /* format and ship a warning message line by mail */
1444 char buf[POPBUFSIZE];
1448 * stuffline() requires its input to be writeable (for CR stripping),
1449 * so we needed to copy the message to a writeable buffer anyway in
1450 * case it was a string constant. We make a virtue of that necessity
1451 * here by supporting stdargs/varargs.
1453 #if defined(HAVE_STDARG_H)
1458 #ifdef HAVE_VSNPRINTF
1459 vsnprintf(buf, sizeof(buf), fmt, ap);
1461 vsprintf(buf, fmt, ap);
1465 #ifdef HAVE_SNPRINTF
1466 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1468 strcat(buf, "\r\n");
1469 #endif /* HAVE_SNPRINTF */
1471 stuffline(ctl, buf);
1474 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
1475 /* sign and send mailed warnings */
1477 stuff_warning(ctl, GT_("--\n\t\t\t\tThe Fetchmail Daemon\n"));
1478 close_sink(ctl, msg, TRUE);
1481 /* sink.c ends here */