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