]> Pileus Git - ~andy/fetchmail/blob - sink.c
Minor corrections.
[~andy/fetchmail] / sink.c
1 /*
2  * sink.c -- forwarding/delivery support for fetchmail
3  *
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.
8  *
9  * Copyright 1998 by Eric S. Raymond
10  * For license terms, see the file COPYING in this directory.
11  */
12
13 #include  "config.h"
14 #include  <stdio.h>
15 #include  <errno.h>
16 #include  <string.h>
17 #include  <signal.h>
18 #include  <time.h>
19 #ifdef HAVE_MEMORY_H
20 #include  <memory.h>
21 #endif /* HAVE_MEMORY_H */
22 #if defined(STDC_HEADERS)
23 #include  <stdlib.h>
24 #endif
25 #if defined(HAVE_UNISTD_H)
26 #include <unistd.h>
27 #endif
28 #if defined(HAVE_STDARG_H)
29 #include  <stdarg.h>
30 #else
31 #include  <varargs.h>
32 #endif
33
34 #include  "fetchmail.h"
35 #include  "socket.h"
36 #include  "smtp.h"
37 #include  "i18n.h"
38
39 /* BSD portability hack...I know, this is an ugly place to put it */
40 #if !defined(SIGCHLD) && defined(SIGCLD)
41 #define SIGCHLD SIGCLD
42 #endif
43
44 /* makes the open_sink()/close_sink() pair non-reentrant */
45 static lmtp_responses;
46
47 static int smtp_open(struct query *ctl)
48 /* try to open a socket to the appropriate SMTP server for this query */ 
49 {
50     /* maybe it's time to close the socket in order to force delivery */
51     if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
52     {
53         close(ctl->smtp_socket);
54         ctl->smtp_socket = -1;
55         batchcount = 0;
56     }
57
58     /* if no socket to any SMTP host is already set up, try to open one */
59     if (ctl->smtp_socket == -1) 
60     {
61         /* 
62          * RFC 1123 requires that the domain name in HELO address is a
63          * "valid principal domain name" for the client host. If we're
64          * running in invisible mode, violate this with malice
65          * aforethought in order to make the Received headers and
66          * logging look right.
67          *
68          * In fact this code relies on the RFC1123 requirement that the
69          * SMTP listener must accept messages even if verification of the
70          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
71          *
72          * How we compute the true mailhost name to pass to the
73          * listener doesn't affect behavior on RFC1123- violating
74          * listeners that check for name match; we're going to lose
75          * on those anyway because we can never give them a name
76          * that matches the local machine fetchmail is running on.
77          * What it will affect is the listener's logging.
78          */
79         struct idlist   *idp;
80         const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
81         int oldphase = phase;
82
83         errno = 0;
84
85         /*
86          * Run down the SMTP hunt list looking for a server that's up.
87          * Use both explicit hunt entries (value TRUE) and implicit 
88          * (default) ones (value FALSE).
89          */
90         oldphase = phase;
91         phase = LISTENER_WAIT;
92
93         set_timeout(ctl->server.timeout);
94         for (idp = ctl->smtphunt; idp; idp = idp->next)
95         {
96             char        *cp, *parsed_host;
97 #ifdef INET6 
98             char        *portnum = SMTP_PORT;
99 #else
100             int         portnum = SMTP_PORT;
101 #endif /* INET6 */
102
103             xalloca(parsed_host, char *, strlen(idp->id) + 1);
104
105             ctl->smtphost = idp->id;  /* remember last host tried. */
106
107             strcpy(parsed_host, idp->id);
108             if ((cp = strrchr(parsed_host, '/')))
109             {
110                 *cp++ = 0;
111 #ifdef INET6 
112                 portnum = cp;
113 #else
114                 portnum = atoi(cp);
115 #endif /* INET6 */
116             }
117
118             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
119                                              ctl->server.plugout)) == -1)
120                 continue;
121
122             /* are we doing SMTP or LMTP? */
123             SMTP_setmode(ctl->listener);
124
125             /* first, probe for ESMTP */
126             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
127                     SMTP_ehlo(ctl->smtp_socket, id_me,
128                           &ctl->server.esmtp_options) == SM_OK)
129                break;  /* success */
130
131             /*
132              * RFC 1869 warns that some listeners hang up on a failed EHLO,
133              * so it's safest not to assume the socket will still be good.
134              */
135             SockClose(ctl->smtp_socket);
136             ctl->smtp_socket = -1;
137
138             /* if opening for ESMTP failed, try SMTP */
139             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
140                                              ctl->server.plugout)) == -1)
141                 continue;
142
143             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
144                     SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
145                 break;  /* success */
146
147             SockClose(ctl->smtp_socket);
148             ctl->smtp_socket = -1;
149         }
150         set_timeout(0);
151         phase = oldphase;
152     }
153
154     /*
155      * RFC 1123 requires that the domain name part of the
156      * RCPT TO address be "canonicalized", that is a FQDN
157      * or MX but not a CNAME.  Some listeners (like exim)
158      * enforce this.  Now that we have the actual hostname,
159      * compute what we should canonicalize with.
160      */
161     ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
162
163     if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
164         error(0, 0, _("forwarding to %s"), ctl->smtphost);
165
166     return(ctl->smtp_socket);
167 }
168
169 /* these are shared by open_sink and stuffline */
170 static FILE *sinkfp;
171 static RETSIGTYPE (*sigchld)(int);
172
173 int stuffline(struct query *ctl, char *buf)
174 /* ship a line to the given control block's output sink (SMTP server or MDA) */
175 {
176     int n, oldphase;
177     char *last;
178
179     /* The line may contain NUL characters. Find the last char to use
180      * -- the real line termination is the sequence "\n\0".
181      */
182     last = buf;
183     while ((last += strlen(last)) && (last[-1] != '\n'))
184         last++;
185
186     /* fix message lines that have only \n termination (for qmail) */
187     if (ctl->forcecr)
188     {
189         if (last - 1 == buf || last[-2] != '\r')
190         {
191             last[-1] = '\r';
192             *last++  = '\n';
193             *last    = '\0';
194         }
195     }
196
197     oldphase = phase;
198     phase = FORWARDING_WAIT;
199
200     /*
201      * SMTP byte-stuffing.  We only do this if the protocol does *not*
202      * use .<CR><LF> as EOM.  If it does, the server will already have
203      * decorated any . lines it sends back up.
204      */
205     if (*buf == '.')
206         if (ctl->server.base_protocol->delimited)       /* server has already byte-stuffed */
207         {
208             if (ctl->mda)
209                 ++buf;
210             else
211                 /* writing to SMTP, leave the byte-stuffing in place */;
212         }
213         else /* if (!protocol->delimited)       -- not byte-stuffed already */
214         {
215             if (!ctl->mda)
216                 SockWrite(ctl->smtp_socket, buf, 1);    /* byte-stuff it */
217             else
218                 /* leave it alone */;
219         }
220
221     /* we may need to strip carriage returns */
222     if (ctl->stripcr)
223     {
224         char    *sp, *tp;
225
226         for (sp = tp = buf; sp < last; sp++)
227             if (*sp != '\r')
228                 *tp++ =  *sp;
229         *tp = '\0';
230         last = tp;
231     }
232
233     n = 0;
234     if (ctl->mda || ctl->bsmtp)
235         n = fwrite(buf, 1, last - buf, sinkfp);
236     else if (ctl->smtp_socket != -1)
237         n = SockWrite(ctl->smtp_socket, buf, last - buf);
238
239     phase = oldphase;
240
241     return(n);
242 }
243
244 static void sanitize(char *s)
245 /* replace unsafe shellchars by an _ */
246 {
247     const static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
248     char *cp;
249
250     for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
251         *cp = '_';
252 }
253
254 static int send_bouncemail(struct msgblk *msg, 
255                            char *message, int nerrors, char *errors[])
256 /* bounce back an error report a la RFC 1892 */
257 {
258     char daemon_name[18 + HOSTLEN] = "FETCHMAIL-DAEMON@";
259     char boundary[BUFSIZ];
260     int i, sock;
261
262     /* don't bounce  in reply to undeliverable bounces */
263     if (!msg->return_path[0] || strcmp(msg->return_path, "<>") == 0)
264         return(FALSE);
265
266     SMTP_setmode(SMTP_MODE);
267
268     strcat(daemon_name, fetchmailhost);
269
270     /* we need only SMTP for this purpose */
271     if ((sock = SockOpen("localhost", SMTP_PORT, NULL, NULL)) == -1
272                 || SMTP_ok(sock) != SM_OK 
273                 || SMTP_helo(sock, "localhost") != SM_OK
274                 || SMTP_from(sock, daemon_name, (char *)NULL) != SM_OK
275                 || SMTP_rcpt(sock, msg->return_path) != SM_OK
276                 || SMTP_data(sock) != SM_OK)
277         return(FALSE);
278
279     sprintf(boundary, 
280             "om-mani-padme-hum-%d-%d-%ld", 
281             getpid(), getppid(), time((time_t *)NULL));
282
283     if (outlevel >= O_VERBOSE)
284         error(0, 0, "SMTP: (bounce-message body)");
285
286     /* bouncemail headers */
287     SockPrintf(sock, "Return-Path: <>");
288     SockPrintf(sock, "From: FETCHMAIL-DAEMON@%s\r\n", fetchmailhost);
289     SockPrintf(sock, "To: %s\n", msg->return_path);
290     SockPrintf(sock, "MIME-Version: 1.0\r\n");
291     SockPrintf(sock, "Content-Type: multipart/report; report-type=delivery-status; boundary=\"%s\"\r\n", boundary);
292     SockPrintf(sock, "\r\n");
293     SockPrintf(sock, "Content-Transfer-Encoding: 7bit\r\n");
294     SockPrintf(sock, "\r\n");
295
296     /* RFC1892 part 1 -- human-readable message */
297     SockPrintf(sock, "--%s\r\n", boundary); 
298     SockPrintf(sock,"Content-Type: text/plain\r\n");
299     SockPrintf(sock, "\r\n");
300     SockWrite(sock, message, strlen(message));
301     SockPrintf(sock, "\r\n");
302     SockPrintf(sock, "\r\n");
303
304     if (nerrors)
305     {
306         /* RFC1892 part 2 -- machine-readable responses */
307         SockPrintf(sock, "--%s\r\n", boundary); 
308         SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
309         SockPrintf(sock, "\r\n");
310         for (i = 0; i < nerrors; i++)
311             SockPrintf(sock, "%s\r\n", errors[i]);
312         SockPrintf(sock, "\r\n");
313     }
314
315     /* RFC1892 part 3 -- headers of undelivered message */
316     SockPrintf(sock, "--%s\r\n", boundary); 
317     SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
318     SockPrintf(sock, "\r\n");
319     SockWrite(sock, msg->headers, strlen(msg->headers));
320     SockPrintf(sock, "\r\n");
321     SockPrintf(sock, "--%s--\r\n", boundary); 
322
323     if (SMTP_eom(sock) != SM_OK || SMTP_quit(sock))
324         return(FALSE);
325
326     SockClose(sock);
327
328     return(TRUE);
329 }
330
331 static int handle_smtp_error(struct query *ctl, struct msgblk *msg)
332 /* handle SMTP errors based on the content of SMTP_response */
333 {
334     int smtperr = atoi(smtp_response);
335     char *responses[1];
336
337     responses[0] = smtp_response;
338
339     /* required by RFC1870; sets us up to be able to send bouncemail */
340     SMTP_rset(ctl->smtp_socket);
341
342     /*
343      * Note: send_bouncemail message strings are not made subject
344      * to gettext translation because (a) they're going to be 
345      * embedded in a text/plain 7bit part, and (b) they're
346      * going to be associated with listener error-response
347      * messages, which are probably in English (none of the
348      * MTAs I know about are internationalized).
349      */
350     if (str_find(&ctl->antispam, smtperr))
351     {
352         /*
353          * SMTP listener explicitly refuses to deliver mail
354          * coming from this address, probably due to an
355          * anti-spam domain exclusion.  Respect this.  Don't
356          * try to ship the message, and don't prevent it from
357          * being deleted.  Typical values:
358          *
359          * 501 = exim's old antispam response
360          * 550 = exim's new antispam response (temporary)
361          * 553 = sendmail 8.8.7's generic REJECT 
362          * 571 = sendmail's "unsolicited email refused"
363          *
364          */
365         send_bouncemail(msg, 
366                         "We do not accept mail from you.\r\n", 
367                         1, responses);
368         return(PS_REFUSED);
369     }
370
371     /*
372      * Suppress error message only if the response specifically 
373      * meant `excluded for policy reasons'.  We *should* see
374      * an error when the return code is less specific.
375      */
376     if (smtperr >= 400)
377         error(0, -1, _("%cMTP error: %s"), 
378               ctl->listener,
379               smtp_response);
380
381     switch (smtperr)
382     {
383     case 452: /* insufficient system storage */
384         /*
385          * Temporary out-of-queue-space condition on the
386          * ESMTP server.  Don't try to ship the message, 
387          * and suppress deletion so it can be retried on
388          * a future retrieval cycle. 
389          *
390          * Bouncemail *might* be appropriate here as a delay
391          * notification.  But it's not really necessary because
392          * this is not an actual failure, we're very likely to be
393          * able to recover on the next cycle.
394          */
395         return(PS_TRANSIENT);
396
397     case 552: /* message exceeds fixed maximum message size */
398         /*
399          * Permanent no-go condition on the
400          * ESMTP server.  Don't try to ship the message, 
401          * and allow it to be deleted.
402          */
403         send_bouncemail(msg, 
404                         "This message was too large.\r\n", 
405                         1, responses);
406         return(PS_REFUSED);
407
408     case 553: /* invalid sending domain */
409         /*
410          * These latter days 553 usually means a spammer is trying to
411          * cover his tracks.
412          */
413         send_bouncemail(msg,
414                         "Invalid address.\r\n", 
415                         1, responses);
416         return(PS_REFUSED);
417
418     default:    /* bounce the error back to the sender */
419         send_bouncemail(msg,
420                         "General SMTP/ESMTP error.\r\n", 
421                         1, responses);
422         return(PS_REFUSED);
423     }
424 }
425
426 int open_sink(struct query *ctl, struct msgblk *msg,
427               int *good_addresses, int *bad_addresses)
428 /* set up sinkfp to be an input sink we can ship a message to */
429 {
430     struct      idlist *idp;
431
432     *bad_addresses = *good_addresses = 0;
433
434     if (ctl->bsmtp)             /* dump to a BSMTP batch file */
435     {
436         if (strcmp(ctl->bsmtp, "-") == 0)
437             sinkfp = stdout;
438         else
439             sinkfp = fopen(ctl->bsmtp, "a");
440
441         /* see the ap computation under the SMTP branch */
442         fprintf(sinkfp, 
443                 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
444
445         if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
446             fputs(" BODY=8BITMIME", sinkfp);
447         else if (ctl->mimemsg & MSG_IS_7BIT)
448             fputs(" BODY=7BIT", sinkfp);
449
450         fprintf(sinkfp, " SIZE=%d\r\n", msg->reallen);
451
452         /*
453          * RFC 1123 requires that the domain name part of the
454          * RCPT TO address be "canonicalized", that is a FQDN
455          * or MX but not a CNAME.  Some listeners (like exim)
456          * enforce this.  Now that we have the actual hostname,
457          * compute what we should canonicalize with.
458          */
459         ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
460
461         *bad_addresses = 0;
462         for (idp = msg->recipients; idp; idp = idp->next)
463             if (idp->val.status.mark == XMIT_ACCEPT)
464             {
465                 if (strchr(idp->id, '@'))
466                     fprintf(sinkfp,
467                                 "RCPT TO: %s\r\n", idp->id);
468                 else
469                     fprintf(sinkfp,
470                                 "RCPT TO: %s@%s\r\n", idp->id, ctl->destaddr);
471                 *good_addresses = 0;
472             }
473
474         fputs("DATA\r\n", sinkfp);
475
476         if (ferror(sinkfp))
477         {
478             error(0, -1, _("BSMTP file open or preamble write failed"));
479             return(PS_BSMTP);
480         }
481     }
482     else if (ctl->mda)          /* we have a declared MDA */
483     {
484         int     length = 0, fromlen = 0, nameslen = 0;
485         char    *names = NULL, *before, *after, *from = NULL;
486
487         ctl->destaddr = "localhost";
488
489         for (idp = msg->recipients; idp; idp = idp->next)
490             if (idp->val.status.mark == XMIT_ACCEPT)
491                 (*good_addresses)++;
492
493         length = strlen(ctl->mda);
494         before = xstrdup(ctl->mda);
495
496         /* get user addresses for %T (or %s for backward compatibility) */
497         if (strstr(before, "%s") || strstr(before, "%T"))
498         {
499             /*
500              * We go through this in order to be able to handle very
501              * long lists of users and (re)implement %s.
502              */
503             nameslen = 0;
504             for (idp = msg->recipients; idp; idp = idp->next)
505                 if ((idp->val.status.mark == XMIT_ACCEPT))
506                     nameslen += (strlen(idp->id) + 1);  /* string + ' ' */
507             if ((*good_addresses == 0))
508                 nameslen = strlen(run.postmaster);
509
510             names = (char *)xmalloc(nameslen + 1);      /* account for '\0' */
511             if (*good_addresses == 0)
512                 strcpy(names, run.postmaster);
513             else
514             {
515                 names[0] = '\0';
516                 for (idp = msg->recipients; idp; idp = idp->next)
517                     if (idp->val.status.mark == XMIT_ACCEPT)
518                     {
519                         strcat(names, idp->id);
520                         strcat(names, " ");
521                     }
522                 names[--nameslen] = '\0';       /* chop trailing space */
523             }
524
525             /* sanitize names in order to contain only harmless shell chars */
526             sanitize(names);
527         }
528
529         /* get From address for %F */
530         if (strstr(before, "%F"))
531         {
532             from = xstrdup(msg->return_path);
533
534             /* sanitize from in order to contain *only* harmless shell chars */
535             sanitize(from);
536
537             fromlen = strlen(from);
538         }
539
540         /* do we have to build an mda string? */
541         if (names || from) 
542         {               
543             char        *sp, *dp;
544
545             /* find length of resulting mda string */
546             sp = before;
547             while ((sp = strstr(sp, "%s"))) {
548                 length += nameslen - 2; /* subtract %s */
549                 sp += 2;
550             }
551             sp = before;
552             while ((sp = strstr(sp, "%T"))) {
553                 length += nameslen - 2; /* subtract %T */
554                 sp += 2;
555             }
556             sp = before;
557             while ((sp = strstr(sp, "%F"))) {
558                 length += fromlen - 2;  /* subtract %F */
559                 sp += 2;
560             }
561                 
562             after = xmalloc(length + 1);
563
564             /* copy mda source string to after, while expanding %[sTF] */
565             for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
566                 if (sp[0] != '%')       continue;
567
568                 /* need to expand? BTW, no here overflow, because in
569                 ** the worst case (end of string) sp[1] == '\0' */
570                 if (sp[1] == 's' || sp[1] == 'T') {
571                     strcpy(dp, names);
572                     dp += nameslen;
573                     sp++;       /* position sp over [sT] */
574                     dp--;       /* adjust dp */
575                 } else if (sp[1] == 'F') {
576                     strcpy(dp, from);
577                     dp += fromlen;
578                     sp++;       /* position sp over F */
579                     dp--;       /* adjust dp */
580                 }
581             }
582
583             if (names) {
584                 free(names);
585                 names = NULL;
586             }
587             if (from) {
588                 free(from);
589                 from = NULL;
590             }
591
592             free(before);
593
594             before = after;
595         }
596
597
598         if (outlevel >= O_DEBUG)
599             error(0, 0, _("about to deliver with: %s"), before);
600
601 #ifdef HAVE_SETEUID
602         /*
603          * Arrange to run with user's permissions if we're root.
604          * This will initialize the ownership of any files the
605          * MDA creates properly.  (The seteuid call is available
606          * under all BSDs and Linux)
607          */
608         seteuid(ctl->uid);
609 #endif /* HAVE_SETEUID */
610
611         sinkfp = popen(before, "w");
612         free(before);
613         before = NULL;
614
615 #ifdef HAVE_SETEUID
616         /* this will fail quietly if we didn't start as root */
617         seteuid(0);
618 #endif /* HAVE_SETEUID */
619
620         if (!sinkfp)
621         {
622             error(0, 0, _("MDA open failed"));
623             return(PS_IOERR);
624         }
625
626         sigchld = signal(SIGCHLD, SIG_DFL);
627     }
628     else /* forward to an SMTP or LMTP listener */
629     {
630         const char      *ap;
631         char            options[MSGBUFSIZE]; 
632         char            addr[HOSTLEN+USERNAMELEN+1];
633         char            **from_responses;
634         int             total_addresses;
635
636         /* build a connection to the SMTP listener */
637         if ((smtp_open(ctl) == -1))
638         {
639             error(0, errno, _("%cMTP connect to %s failed"),
640                   ctl->listener,
641                   ctl->smtphost ? ctl->smtphost : "localhost");
642             return(PS_SMTP);
643         }
644
645         /*
646          * Compute ESMTP options.
647          */
648         options[0] = '\0';
649         if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
650              if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
651                 strcpy(options, " BODY=8BITMIME");
652              else if (ctl->mimemsg & MSG_IS_7BIT)
653                 strcpy(options, " BODY=7BIT");
654         }
655
656         if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
657             sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
658
659         /*
660          * Try to get the SMTP listener to take the Return-Path
661          * address as MAIL FROM .  If it won't, fall back on the
662          * calling-user ID.  This won't affect replies, which use the
663          * header From address anyway.
664          *
665          * RFC 1123 requires that the domain name part of the
666          * MAIL FROM address be "canonicalized", that is a
667          * FQDN or MX but not a CNAME.  We'll assume the From
668          * header is already in this form here (it certainly
669          * is if rewrite is on).  RFC 1123 is silent on whether
670          * a nonexistent hostname part is considered canonical.
671          *
672          * This is a potential problem if the MTAs further upstream
673          * didn't pass canonicalized From/Return-Path lines, *and* the
674          * local SMTP listener insists on them.
675          */
676         ap = (msg->return_path[0]) ? msg->return_path : user;
677         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
678             return(handle_smtp_error(ctl, msg));
679
680         /*
681          * Now list the recipient addressees
682          */
683         total_addresses = 0;
684         for (idp = msg->recipients; idp; idp = idp->next)
685             total_addresses++;
686         xalloca(from_responses, char **, sizeof(char *) * total_addresses);
687         for (idp = msg->recipients; idp; idp = idp->next)
688             if (idp->val.status.mark == XMIT_ACCEPT)
689             {
690                 if (strchr(idp->id, '@'))
691                     strcpy(addr, idp->id);
692                 else
693 #ifdef HAVE_SNPRINTF
694                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, ctl->destaddr);
695 #else
696                     sprintf(addr, "%s@%s", idp->id, ctl->destaddr);
697 #endif /* HAVE_SNPRINTF */
698
699                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
700                     (*good_addresses)++;
701                 else
702                 {
703                     char        errbuf[POPBUFSIZE];
704
705                     strcpy(errbuf, idp->id);
706                     strcat(errbuf, ": ");
707                     strcat(errbuf, smtp_response);
708
709                     xalloca(from_responses[*bad_addresses], 
710                             char *, 
711                             strlen(errbuf)+1);
712                     strcpy(from_responses[*bad_addresses], errbuf);
713
714                     (*bad_addresses)++;
715                     idp->val.status.mark = XMIT_RCPTBAD;
716                     if (outlevel >= O_VERBOSE)
717                         error(0, 0, 
718                               _("%cMTP listener doesn't like recipient address `%s'"),
719                               ctl->listener, addr);
720                 }
721             }
722         if (*bad_addresses)
723             send_bouncemail(msg, 
724                             "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
725                             *bad_addresses, from_responses);
726         /*
727          * It's tempting to do local notification only if bouncemail was
728          * insufficient -- that is, to add && total_addresses > *bad_addresses
729          * to the test here.  The problem with this theory is that it would
730          * make initial diagnosis of a broken multidrop configuration very
731          * hard -- most single-recipient messages would just invisibly bounce.
732          */
733         if (!(*good_addresses)) 
734         {
735             if (strchr(run.postmaster, '@'))
736                 strcpy(addr, run.postmaster);
737             else
738             {
739 #ifdef HAVE_SNPRINTF
740                 snprintf(addr, sizeof(addr)-1, "%s@%s", run.postmaster, ctl->destaddr);
741 #else
742                 sprintf(addr, "%s@%s", run.postmaster, ctl->destaddr);
743 #endif /* HAVE_SNPRINTF */
744             }
745
746             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
747             {
748                 error(0, 0, _("can't even send to %s!"), run.postmaster);
749                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
750                 return(PS_SMTP);
751             }
752
753             if (outlevel >= O_VERBOSE)
754                 error(0, 0, _("no address matches; forwarding to %s."), run.postmaster);
755         }
756
757         /* 
758          * Tell the listener we're ready to send data.
759          * Some listeners (like zmailer) may return antispam errors here.
760          */
761         if (SMTP_data(ctl->smtp_socket) != SM_OK)
762             return(handle_smtp_error(ctl, msg));
763     }
764
765     /*
766      * We need to stash this away in order to know how many
767      * response lines to expect after the LMTP end-of-message.
768      */
769     lmtp_responses = *good_addresses;
770
771     return(PS_SUCCESS);
772 }
773
774 void release_sink(struct query *ctl)
775 /* release the per-message output sink, whether it's a pipe or SMTP socket */
776 {
777     if (ctl->bsmtp)
778         fclose(sinkfp);
779     else if (ctl->mda)
780     {
781         if (sinkfp)
782         {
783             pclose(sinkfp);
784             sinkfp = (FILE *)NULL;
785         }
786         signal(SIGCHLD, sigchld);
787     }
788 }
789
790 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
791 /* perform end-of-message actions on the current output sink */
792 {
793     if (ctl->mda)
794     {
795         int rc;
796
797         /* close the delivery pipe, we'll reopen before next message */
798         if (sinkfp)
799         {
800             rc = pclose(sinkfp);
801             sinkfp = (FILE *)NULL;
802         }
803         else
804             rc = 0;
805         signal(SIGCHLD, sigchld);
806         if (rc)
807         {
808             error(0, -1, _("MDA exited abnormally or returned nonzero status"));
809             return(FALSE);
810         }
811     }
812     else if (ctl->bsmtp)
813     {
814         /* implicit disk-full check here... */
815         fputs("..\r\n", sinkfp);
816         if (strcmp(ctl->bsmtp, "-"))
817             fclose(sinkfp);
818         if (ferror(sinkfp))
819         {
820             error(0, -1, _("Message termination or close of BSMTP file failed"));
821             return(FALSE);
822         }
823     }
824     else if (forward)
825     {
826         /* write message terminator */
827         if (SMTP_eom(ctl->smtp_socket) != SM_OK)
828         {
829             error(0, -1, _("SMTP listener refused delivery"));
830             return(FALSE);
831         }
832
833         /*
834          * If this is an SMTP connection, SMTP_eom() ate the response.
835          * But could be this is an LMTP connection, in which case we have to
836          * interpret either (a) a single 503 response meaning there
837          * were no successful RCPT TOs, or (b) a variable number of
838          * responses, one for each successful RCPT TO.  We need to send
839          * bouncemail on each failed response and then return TRUE anyway,
840          * otherwise the message will get left in the queue and resent
841          * to people who got it the first time.
842          */
843         if (ctl->listener == LMTP_MODE)
844             if (lmtp_responses == 0)
845             {
846                 SMTP_ok(ctl->smtp_socket); 
847
848                 /*
849                  * According to RFC2033, 503 is the only legal response
850                  * if no RCPT TO commands succeeded.  No error recovery
851                  * is really possible here, as we have no idea what
852                  * insane thing the listener might be doing if it doesn't
853                  * comply.
854                  */
855                 if (atoi(smtp_response) == 503)
856                     error(0, -1, _("LMTP delivery error on EOM"));
857                 else
858                     error(0, -1,
859                           _("Unexpected non-503 response to LMTP EOM: %s"),
860                           smtp_response);
861
862                 /*
863                  * It's not completely clear what to do here.  We choose to
864                  * interpret delivery failure here as a transient error, 
865                  * the same way SMTP delivery failure is handled.  If we're
866                  * wrong, an undead message will get stuck in the queue.
867                  */
868                 return(FALSE);
869             }
870             else
871             {
872                 int     i, errors;
873                 char    **responses;
874
875                 /* eat the RFC2033-required responses, saving errors */ 
876                 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
877                 for (errors = i = 0; i < lmtp_responses; i++)
878                 {
879                     if (SMTP_ok(ctl->smtp_socket) == SM_OK)
880                         responses[i] = (char *)NULL;
881                     else
882                     {
883                         xalloca(responses[errors], 
884                                 char *, 
885                                 strlen(smtp_response)+1);
886                         strcpy(responses[errors], smtp_response);
887                         errors++;
888                     }
889                 }
890
891                 if (errors == 0)
892                     return(TRUE);       /* all deliveries succeeded */
893                 else
894                     /*
895                      * One or more deliveries failed.
896                      * If we can bounce a failures list back to the sender,
897                      * return TRUE, deleting the message from the server so
898                      * it won't be re-forwarded on subsequent poll cycles.
899                      */
900                     return(send_bouncemail(msg,
901                                    "LSMTP partial delivery failure.\r\n",
902                                    errors, responses));
903             }
904     }
905
906     return(TRUE);
907 }
908
909 int open_warning_by_mail(struct query *ctl, struct msgblk *msg)
910 /* set up output sink for a mailed warning to calling user */
911 {
912     int good, bad;
913
914     /*
915      * Dispatching warning email is a little complicated.  The problem is
916      * that we have to deal with three distinct cases:
917      *
918      * 1. Single-drop running from user account.  Warning mail should
919      * go to the local name for which we're collecting (coincides
920      * with calling user).
921      *
922      * 2. Single-drop running from root or other privileged ID, with rc
923      * file generated on the fly (Ken Estes's weird setup...)  Mail
924      * should go to the local name for which we're collecting (does not 
925      * coincide with calling user).
926      * 
927      * 3. Multidrop.  Mail must go to postmaster.  We leave the recipients
928      * member null so this message will fall through to run.postmaster.
929      *
930      * The zero in the reallen element means we won't pass a SIZE
931      * option to ESMTP; the message length would be more trouble than
932      * it's worth to compute.
933      */
934     struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON", 0};
935
936     if (!MULTIDROP(ctl))                /* send to calling user */
937     {
938         int status;
939
940         save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
941         status = open_sink(ctl, &reply, &good, &bad);
942         free_str_list(&reply.recipients);
943         return(status);
944     }
945     else                                /* send to postmaster  */
946         return(open_sink(ctl, &reply, &good, &bad));
947 }
948
949 #if defined(HAVE_STDARG_H)
950 void stuff_warning(struct query *ctl, const char *fmt, ... )
951 #else
952 void stuff_warning(struct query *ctl, fmt, va_alist)
953 struct query *ctl;
954 const char *fmt;        /* printf-style format */
955 va_dcl
956 #endif
957 /* format and ship a warning message line by mail */
958 {
959     char        buf[POPBUFSIZE];
960     va_list ap;
961
962     /*
963      * stuffline() requires its input to be writeable (for CR stripping),
964      * so we needed to copy the message to a writeable buffer anyway in
965      * case it was a string constant.  We make a virtue of that necessity
966      * here by supporting stdargs/varargs.
967      */
968 #if defined(HAVE_STDARG_H)
969     va_start(ap, fmt) ;
970 #else
971     va_start(ap);
972 #endif
973 #ifdef HAVE_VSNPRINTF
974     vsnprintf(buf, sizeof(buf), fmt, ap);
975 #else
976     vsprintf(buf, fmt, ap);
977 #endif
978     va_end(ap);
979
980     strcat(buf, "\r\n");
981
982     stuffline(ctl, buf);
983 }
984
985 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
986 /* sign and send mailed warnings */
987 {
988     stuff_warning(ctl, "--\r\n\t\t\t\tThe Fetchmail Daemon\r\n");
989     close_sink(ctl, msg, TRUE);
990 }
991
992 /* sink.c ends here */