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