]> Pileus Git - ~andy/fetchmail/blob - sink.c
Full RFC1894 conformance.
[~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, int userclass,
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         struct idlist   *idp;
307         int             nusers;
308         
309         /* RFC1892 part 2 -- machine-readable responses */
310         SockPrintf(sock, "--%s\r\n", boundary); 
311         SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
312         SockPrintf(sock, "\r\n");
313         SockPrintf(sock, "Reporting-MTA: dns; %s\r\n", fetchmailhost);
314
315         nusers = 0;
316         for (idp = msg->recipients; idp; idp = idp->next)
317             if (idp->val.status.mark == userclass)
318             {
319                 char    *error;
320                 /* Minimum RFC1894 compliance + Diagnostic-Code field */
321                 SockPrintf(sock, "\r\n");
322                 SockPrintf(sock, "Final-Recipient: rfc822; %s\r\n", idp->id);
323                 SockPrintf(sock, "Action: failed\r\n");
324
325                 if (nerrors == 1)
326                     /* one error applies to all users */
327                     error = errors[0];
328                 else if (nerrors > nusers)
329                 {
330                     SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
331                     break;
332                 }
333                 else
334                     /* errors correspond 1-1 to selected users */
335                     error = errors[nusers++];
336                 
337                 if (strlen(error) > 9 && isdigit(error[4])
338                         && error[5] == '.' && isdigit(error[6])
339                         && error[7] == '.' && isdigit(error[8]))
340                     /* Enhanced status code available, use it */
341                     SockPrintf(sock, "Status: %5.5s\r\n", &(error[4]));
342                 else
343                     /* Enhanced status code not available, fake one */
344                     SockPrintf(sock, "Status: %c.0.0\r\n", error[0]);
345                 SockPrintf(sock, "Diagnostic-Code: %s\r\n", error);
346             }
347         SockPrintf(sock, "\r\n");
348     }
349
350     /* RFC1892 part 3 -- headers of undelivered message */
351     SockPrintf(sock, "--%s\r\n", boundary); 
352     SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
353     SockPrintf(sock, "\r\n");
354     SockWrite(sock, msg->headers, strlen(msg->headers));
355     SockPrintf(sock, "\r\n");
356     SockPrintf(sock, "--%s--\r\n", boundary); 
357
358     if (SMTP_eom(sock) != SM_OK || SMTP_quit(sock))
359         return(FALSE);
360
361     SockClose(sock);
362
363     return(TRUE);
364 }
365
366 static int handle_smtp_error(struct query *ctl, struct msgblk *msg)
367 /* handle SMTP errors based on the content of SMTP_response */
368 {
369     int smtperr = atoi(smtp_response);
370     char *responses[1];
371
372     responses[0] = smtp_response;
373
374     /* required by RFC1870; sets us up to be able to send bouncemail */
375     SMTP_rset(ctl->smtp_socket);
376
377     /*
378      * Note: send_bouncemail message strings are not made subject
379      * to gettext translation because (a) they're going to be 
380      * embedded in a text/plain 7bit part, and (b) they're
381      * going to be associated with listener error-response
382      * messages, which are probably in English (none of the
383      * MTAs I know about are internationalized).
384      */
385     if (str_find(&ctl->antispam, smtperr))
386     {
387         /*
388          * SMTP listener explicitly refuses to deliver mail
389          * coming from this address, probably due to an
390          * anti-spam domain exclusion.  Respect this.  Don't
391          * try to ship the message, and don't prevent it from
392          * being deleted.  Typical values:
393          *
394          * 501 = exim's old antispam response
395          * 550 = exim's new antispam response (temporary)
396          * 553 = sendmail 8.8.7's generic REJECT 
397          * 571 = sendmail's "unsolicited email refused"
398          *
399          */
400         send_bouncemail(msg, XMIT_ACCEPT,
401                         "Our spam filter rejected this transaction.\r\n", 
402                         1, responses);
403         return(PS_REFUSED);
404     }
405
406     /*
407      * Suppress error message only if the response specifically 
408      * meant `excluded for policy reasons'.  We *should* see
409      * an error when the return code is less specific.
410      */
411     if (smtperr >= 400)
412         error(0, -1, _("%cMTP error: %s"), 
413               ctl->listener,
414               smtp_response);
415
416     switch (smtperr)
417     {
418     case 452: /* insufficient system storage */
419         /*
420          * Temporary out-of-queue-space condition on the
421          * ESMTP server.  Don't try to ship the message, 
422          * and suppress deletion so it can be retried on
423          * a future retrieval cycle. 
424          *
425          * Bouncemail *might* be appropriate here as a delay
426          * notification.  But it's not really necessary because
427          * this is not an actual failure, we're very likely to be
428          * able to recover on the next cycle.
429          */
430         return(PS_TRANSIENT);
431
432     case 552: /* message exceeds fixed maximum message size */
433         /*
434          * Permanent no-go condition on the
435          * ESMTP server.  Don't try to ship the message, 
436          * and allow it to be deleted.
437          */
438         send_bouncemail(msg, XMIT_ACCEPT,
439                         "This message was too large.\r\n", 
440                         1, responses);
441         return(PS_REFUSED);
442
443     case 553: /* invalid sending domain */
444         /*
445          * These latter days 553 usually means a spammer is trying to
446          * cover his tracks.
447          */
448         send_bouncemail(msg, XMIT_ACCEPT,
449                         "Invalid address.\r\n", 
450                         1, responses);
451         return(PS_REFUSED);
452
453     default:    /* bounce the error back to the sender */
454         send_bouncemail(msg, XMIT_ACCEPT,
455                         "General SMTP/ESMTP error.\r\n", 
456                         1, responses);
457         return(PS_REFUSED);
458     }
459 }
460
461 int open_sink(struct query *ctl, struct msgblk *msg,
462               int *good_addresses, int *bad_addresses)
463 /* set up sinkfp to be an input sink we can ship a message to */
464 {
465     struct      idlist *idp;
466
467     *bad_addresses = *good_addresses = 0;
468
469     if (ctl->bsmtp)             /* dump to a BSMTP batch file */
470     {
471         if (strcmp(ctl->bsmtp, "-") == 0)
472             sinkfp = stdout;
473         else
474             sinkfp = fopen(ctl->bsmtp, "a");
475
476         /* see the ap computation under the SMTP branch */
477         fprintf(sinkfp, 
478                 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
479
480         if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
481             fputs(" BODY=8BITMIME", sinkfp);
482         else if (ctl->mimemsg & MSG_IS_7BIT)
483             fputs(" BODY=7BIT", sinkfp);
484
485         fprintf(sinkfp, " SIZE=%d\r\n", msg->reallen);
486
487         /*
488          * RFC 1123 requires that the domain name part of the
489          * RCPT TO address be "canonicalized", that is a FQDN
490          * or MX but not a CNAME.  Some listeners (like exim)
491          * enforce this.  Now that we have the actual hostname,
492          * compute what we should canonicalize with.
493          */
494         ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
495
496         *bad_addresses = 0;
497         for (idp = msg->recipients; idp; idp = idp->next)
498             if (idp->val.status.mark == XMIT_ACCEPT)
499             {
500                 if (strchr(idp->id, '@'))
501                     fprintf(sinkfp,
502                                 "RCPT TO: %s\r\n", idp->id);
503                 else
504                     fprintf(sinkfp,
505                                 "RCPT TO: %s@%s\r\n", idp->id, ctl->destaddr);
506                 *good_addresses = 0;
507             }
508
509         fputs("DATA\r\n", sinkfp);
510
511         if (ferror(sinkfp))
512         {
513             error(0, -1, _("BSMTP file open or preamble write failed"));
514             return(PS_BSMTP);
515         }
516     }
517     else if (ctl->mda)          /* we have a declared MDA */
518     {
519         int     length = 0, fromlen = 0, nameslen = 0;
520         char    *names = NULL, *before, *after, *from = NULL;
521
522         ctl->destaddr = "localhost";
523
524         for (idp = msg->recipients; idp; idp = idp->next)
525             if (idp->val.status.mark == XMIT_ACCEPT)
526                 (*good_addresses)++;
527
528         length = strlen(ctl->mda);
529         before = xstrdup(ctl->mda);
530
531         /* get user addresses for %T (or %s for backward compatibility) */
532         if (strstr(before, "%s") || strstr(before, "%T"))
533         {
534             /*
535              * We go through this in order to be able to handle very
536              * long lists of users and (re)implement %s.
537              */
538             nameslen = 0;
539             for (idp = msg->recipients; idp; idp = idp->next)
540                 if ((idp->val.status.mark == XMIT_ACCEPT))
541                     nameslen += (strlen(idp->id) + 1);  /* string + ' ' */
542             if ((*good_addresses == 0))
543                 nameslen = strlen(run.postmaster);
544
545             names = (char *)xmalloc(nameslen + 1);      /* account for '\0' */
546             if (*good_addresses == 0)
547                 strcpy(names, run.postmaster);
548             else
549             {
550                 names[0] = '\0';
551                 for (idp = msg->recipients; idp; idp = idp->next)
552                     if (idp->val.status.mark == XMIT_ACCEPT)
553                     {
554                         strcat(names, idp->id);
555                         strcat(names, " ");
556                     }
557                 names[--nameslen] = '\0';       /* chop trailing space */
558             }
559
560             /* sanitize names in order to contain only harmless shell chars */
561             sanitize(names);
562         }
563
564         /* get From address for %F */
565         if (strstr(before, "%F"))
566         {
567             from = xstrdup(msg->return_path);
568
569             /* sanitize from in order to contain *only* harmless shell chars */
570             sanitize(from);
571
572             fromlen = strlen(from);
573         }
574
575         /* do we have to build an mda string? */
576         if (names || from) 
577         {               
578             char        *sp, *dp;
579
580             /* find length of resulting mda string */
581             sp = before;
582             while ((sp = strstr(sp, "%s"))) {
583                 length += nameslen - 2; /* subtract %s */
584                 sp += 2;
585             }
586             sp = before;
587             while ((sp = strstr(sp, "%T"))) {
588                 length += nameslen - 2; /* subtract %T */
589                 sp += 2;
590             }
591             sp = before;
592             while ((sp = strstr(sp, "%F"))) {
593                 length += fromlen - 2;  /* subtract %F */
594                 sp += 2;
595             }
596                 
597             after = xmalloc(length + 1);
598
599             /* copy mda source string to after, while expanding %[sTF] */
600             for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
601                 if (sp[0] != '%')       continue;
602
603                 /* need to expand? BTW, no here overflow, because in
604                 ** the worst case (end of string) sp[1] == '\0' */
605                 if (sp[1] == 's' || sp[1] == 'T') {
606                     strcpy(dp, names);
607                     dp += nameslen;
608                     sp++;       /* position sp over [sT] */
609                     dp--;       /* adjust dp */
610                 } else if (sp[1] == 'F') {
611                     strcpy(dp, from);
612                     dp += fromlen;
613                     sp++;       /* position sp over F */
614                     dp--;       /* adjust dp */
615                 }
616             }
617
618             if (names) {
619                 free(names);
620                 names = NULL;
621             }
622             if (from) {
623                 free(from);
624                 from = NULL;
625             }
626
627             free(before);
628
629             before = after;
630         }
631
632
633         if (outlevel >= O_DEBUG)
634             error(0, 0, _("about to deliver with: %s"), before);
635
636 #ifdef HAVE_SETEUID
637         /*
638          * Arrange to run with user's permissions if we're root.
639          * This will initialize the ownership of any files the
640          * MDA creates properly.  (The seteuid call is available
641          * under all BSDs and Linux)
642          */
643         seteuid(ctl->uid);
644 #endif /* HAVE_SETEUID */
645
646         sinkfp = popen(before, "w");
647         free(before);
648         before = NULL;
649
650 #ifdef HAVE_SETEUID
651         /* this will fail quietly if we didn't start as root */
652         seteuid(0);
653 #endif /* HAVE_SETEUID */
654
655         if (!sinkfp)
656         {
657             error(0, 0, _("MDA open failed"));
658             return(PS_IOERR);
659         }
660
661         sigchld = signal(SIGCHLD, SIG_DFL);
662     }
663     else /* forward to an SMTP or LMTP listener */
664     {
665         const char      *ap;
666         char            options[MSGBUFSIZE]; 
667         char            addr[HOSTLEN+USERNAMELEN+1];
668         char            **from_responses;
669         int             total_addresses;
670
671         /* build a connection to the SMTP listener */
672         if ((smtp_open(ctl) == -1))
673         {
674             error(0, errno, _("%cMTP connect to %s failed"),
675                   ctl->listener,
676                   ctl->smtphost ? ctl->smtphost : "localhost");
677             return(PS_SMTP);
678         }
679
680         /*
681          * Compute ESMTP options.
682          */
683         options[0] = '\0';
684         if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
685              if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
686                 strcpy(options, " BODY=8BITMIME");
687              else if (ctl->mimemsg & MSG_IS_7BIT)
688                 strcpy(options, " BODY=7BIT");
689         }
690
691         if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
692             sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
693
694         /*
695          * Try to get the SMTP listener to take the Return-Path
696          * address as MAIL FROM .  If it won't, fall back on the
697          * calling-user ID.  This won't affect replies, which use the
698          * header From address anyway.
699          *
700          * RFC 1123 requires that the domain name part of the
701          * MAIL FROM address be "canonicalized", that is a
702          * FQDN or MX but not a CNAME.  We'll assume the From
703          * header is already in this form here (it certainly
704          * is if rewrite is on).  RFC 1123 is silent on whether
705          * a nonexistent hostname part is considered canonical.
706          *
707          * This is a potential problem if the MTAs further upstream
708          * didn't pass canonicalized From/Return-Path lines, *and* the
709          * local SMTP listener insists on them.
710          */
711         ap = (msg->return_path[0]) ? msg->return_path : user;
712         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
713             return(handle_smtp_error(ctl, msg));
714
715         /*
716          * Now list the recipient addressees
717          */
718         total_addresses = 0;
719         for (idp = msg->recipients; idp; idp = idp->next)
720             total_addresses++;
721         xalloca(from_responses, char **, sizeof(char *) * total_addresses);
722         for (idp = msg->recipients; idp; idp = idp->next)
723             if (idp->val.status.mark == XMIT_ACCEPT)
724             {
725                 if (strchr(idp->id, '@'))
726                     strcpy(addr, idp->id);
727                 else
728 #ifdef HAVE_SNPRINTF
729                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, ctl->destaddr);
730 #else
731                     sprintf(addr, "%s@%s", idp->id, ctl->destaddr);
732 #endif /* HAVE_SNPRINTF */
733
734                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
735                     (*good_addresses)++;
736                 else
737                 {
738                     char        errbuf[POPBUFSIZE];
739
740                     strcpy(errbuf, idp->id);
741                     strcat(errbuf, ": ");
742                     strcat(errbuf, smtp_response);
743
744                     xalloca(from_responses[*bad_addresses], 
745                             char *, 
746                             strlen(errbuf)+1);
747                     strcpy(from_responses[*bad_addresses], errbuf);
748
749                     (*bad_addresses)++;
750                     idp->val.status.mark = XMIT_RCPTBAD;
751                     if (outlevel >= O_VERBOSE)
752                         error(0, 0, 
753                               _("%cMTP listener doesn't like recipient address `%s'"),
754                               ctl->listener, addr);
755                 }
756             }
757         if (*bad_addresses)
758             send_bouncemail(msg, XMIT_RCPTBAD,
759                             "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
760                             *bad_addresses, from_responses);
761         /*
762          * It's tempting to do local notification only if bouncemail was
763          * insufficient -- that is, to add && total_addresses > *bad_addresses
764          * to the test here.  The problem with this theory is that it would
765          * make initial diagnosis of a broken multidrop configuration very
766          * hard -- most single-recipient messages would just invisibly bounce.
767          */
768         if (!(*good_addresses)) 
769         {
770             if (strchr(run.postmaster, '@'))
771                 strcpy(addr, run.postmaster);
772             else
773             {
774 #ifdef HAVE_SNPRINTF
775                 snprintf(addr, sizeof(addr)-1, "%s@%s", run.postmaster, ctl->destaddr);
776 #else
777                 sprintf(addr, "%s@%s", run.postmaster, ctl->destaddr);
778 #endif /* HAVE_SNPRINTF */
779             }
780
781             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
782             {
783                 error(0, 0, _("can't even send to %s!"), run.postmaster);
784                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
785                 return(PS_SMTP);
786             }
787
788             if (outlevel >= O_VERBOSE)
789                 error(0, 0, _("no address matches; forwarding to %s."), run.postmaster);
790         }
791
792         /* 
793          * Tell the listener we're ready to send data.
794          * Some listeners (like zmailer) may return antispam errors here.
795          */
796         if (SMTP_data(ctl->smtp_socket) != SM_OK)
797             return(handle_smtp_error(ctl, msg));
798     }
799
800     /*
801      * We need to stash this away in order to know how many
802      * response lines to expect after the LMTP end-of-message.
803      */
804     lmtp_responses = *good_addresses;
805
806     return(PS_SUCCESS);
807 }
808
809 void release_sink(struct query *ctl)
810 /* release the per-message output sink, whether it's a pipe or SMTP socket */
811 {
812     if (ctl->bsmtp)
813         fclose(sinkfp);
814     else if (ctl->mda)
815     {
816         if (sinkfp)
817         {
818             pclose(sinkfp);
819             sinkfp = (FILE *)NULL;
820         }
821         signal(SIGCHLD, sigchld);
822     }
823 }
824
825 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
826 /* perform end-of-message actions on the current output sink */
827 {
828     if (ctl->mda)
829     {
830         int rc;
831
832         /* close the delivery pipe, we'll reopen before next message */
833         if (sinkfp)
834         {
835             rc = pclose(sinkfp);
836             sinkfp = (FILE *)NULL;
837         }
838         else
839             rc = 0;
840         signal(SIGCHLD, sigchld);
841         if (rc)
842         {
843             error(0, -1, _("MDA exited abnormally or returned nonzero status"));
844             return(FALSE);
845         }
846     }
847     else if (ctl->bsmtp)
848     {
849         /* implicit disk-full check here... */
850         fputs("..\r\n", sinkfp);
851         if (strcmp(ctl->bsmtp, "-"))
852             fclose(sinkfp);
853         if (ferror(sinkfp))
854         {
855             error(0, -1, _("Message termination or close of BSMTP file failed"));
856             return(FALSE);
857         }
858     }
859     else if (forward)
860     {
861         /* write message terminator */
862         if (SMTP_eom(ctl->smtp_socket) != SM_OK)
863         {
864             if (handle_smtp_error(ctl, msg) != PS_REFUSED)
865                 return(FALSE);
866             else
867             {
868                 error(0, -1, _("SMTP listener refused delivery"));
869                 return(TRUE);
870             }
871         }
872
873         /*
874          * If this is an SMTP connection, SMTP_eom() ate the response.
875          * But could be this is an LMTP connection, in which case we have to
876          * interpret either (a) a single 503 response meaning there
877          * were no successful RCPT TOs, or (b) a variable number of
878          * responses, one for each successful RCPT TO.  We need to send
879          * bouncemail on each failed response and then return TRUE anyway,
880          * otherwise the message will get left in the queue and resent
881          * to people who got it the first time.
882          */
883         if (ctl->listener == LMTP_MODE)
884             if (lmtp_responses == 0)
885             {
886                 SMTP_ok(ctl->smtp_socket); 
887
888                 /*
889                  * According to RFC2033, 503 is the only legal response
890                  * if no RCPT TO commands succeeded.  No error recovery
891                  * is really possible here, as we have no idea what
892                  * insane thing the listener might be doing if it doesn't
893                  * comply.
894                  */
895                 if (atoi(smtp_response) == 503)
896                     error(0, -1, _("LMTP delivery error on EOM"));
897                 else
898                     error(0, -1,
899                           _("Unexpected non-503 response to LMTP EOM: %s"),
900                           smtp_response);
901
902                 /*
903                  * It's not completely clear what to do here.  We choose to
904                  * interpret delivery failure here as a transient error, 
905                  * the same way SMTP delivery failure is handled.  If we're
906                  * wrong, an undead message will get stuck in the queue.
907                  */
908                 return(FALSE);
909             }
910             else
911             {
912                 int     i, errors;
913                 char    **responses;
914
915                 /* eat the RFC2033-required responses, saving errors */ 
916                 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
917                 for (errors = i = 0; i < lmtp_responses; i++)
918                 {
919                     if (SMTP_ok(ctl->smtp_socket) == SM_OK)
920                         responses[i] = (char *)NULL;
921                     else
922                     {
923                         xalloca(responses[errors], 
924                                 char *, 
925                                 strlen(smtp_response)+1);
926                         strcpy(responses[errors], smtp_response);
927                         errors++;
928                     }
929                 }
930
931                 if (errors == 0)
932                     return(TRUE);       /* all deliveries succeeded */
933                 else
934                     /*
935                      * One or more deliveries failed.
936                      * If we can bounce a failures list back to the sender,
937                      * return TRUE, deleting the message from the server so
938                      * it won't be re-forwarded on subsequent poll cycles.
939                      */
940                     return(send_bouncemail(msg, XMIT_ACCEPT,
941                                    "LSMTP partial delivery failure.\r\n",
942                                    errors, responses));
943             }
944     }
945
946     return(TRUE);
947 }
948
949 int open_warning_by_mail(struct query *ctl, struct msgblk *msg)
950 /* set up output sink for a mailed warning to calling user */
951 {
952     int good, bad;
953
954     /*
955      * Dispatching warning email is a little complicated.  The problem is
956      * that we have to deal with three distinct cases:
957      *
958      * 1. Single-drop running from user account.  Warning mail should
959      * go to the local name for which we're collecting (coincides
960      * with calling user).
961      *
962      * 2. Single-drop running from root or other privileged ID, with rc
963      * file generated on the fly (Ken Estes's weird setup...)  Mail
964      * should go to the local name for which we're collecting (does not 
965      * coincide with calling user).
966      * 
967      * 3. Multidrop.  Mail must go to postmaster.  We leave the recipients
968      * member null so this message will fall through to run.postmaster.
969      *
970      * The zero in the reallen element means we won't pass a SIZE
971      * option to ESMTP; the message length would be more trouble than
972      * it's worth to compute.
973      */
974     struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON", 0};
975
976     if (!MULTIDROP(ctl))                /* send to calling user */
977     {
978         int status;
979
980         save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
981         status = open_sink(ctl, &reply, &good, &bad);
982         free_str_list(&reply.recipients);
983         return(status);
984     }
985     else                                /* send to postmaster  */
986         return(open_sink(ctl, &reply, &good, &bad));
987 }
988
989 #if defined(HAVE_STDARG_H)
990 void stuff_warning(struct query *ctl, const char *fmt, ... )
991 #else
992 void stuff_warning(struct query *ctl, fmt, va_alist)
993 struct query *ctl;
994 const char *fmt;        /* printf-style format */
995 va_dcl
996 #endif
997 /* format and ship a warning message line by mail */
998 {
999     char        buf[POPBUFSIZE];
1000     va_list ap;
1001
1002     /*
1003      * stuffline() requires its input to be writeable (for CR stripping),
1004      * so we needed to copy the message to a writeable buffer anyway in
1005      * case it was a string constant.  We make a virtue of that necessity
1006      * here by supporting stdargs/varargs.
1007      */
1008 #if defined(HAVE_STDARG_H)
1009     va_start(ap, fmt) ;
1010 #else
1011     va_start(ap);
1012 #endif
1013 #ifdef HAVE_VSNPRINTF
1014     vsnprintf(buf, sizeof(buf), fmt, ap);
1015 #else
1016     vsprintf(buf, fmt, ap);
1017 #endif
1018     va_end(ap);
1019
1020     strcat(buf, "\r\n");
1021
1022     stuffline(ctl, buf);
1023 }
1024
1025 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
1026 /* sign and send mailed warnings */
1027 {
1028     stuff_warning(ctl, "--\r\n\t\t\t\tThe Fetchmail Daemon\r\n");
1029     close_sink(ctl, msg, TRUE);
1030 }
1031
1032 /* sink.c ends here */