]> Pileus Git - ~andy/fetchmail/blob - sink.c
Fix bounce message detail regression from 6.3.0.
[~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 #include  <ctype.h>
33 #include  <langinfo.h>
34
35 #include  "fetchmail.h"
36
37 /* for W* macros after pclose() */
38 #define _USE_BSD
39 #include <sys/types.h>
40 #include <sys/resource.h>
41 #include <sys/wait.h>
42
43 #include  "socket.h"
44 #include  "smtp.h"
45 #include  "i18n.h"
46
47 /* BSD portability hack...I know, this is an ugly place to put it */
48 #if !defined(SIGCHLD) && defined(SIGCLD)
49 #define SIGCHLD SIGCLD
50 #endif
51
52 /* makes the open_sink()/close_sink() pair non-reentrant */
53 static int lmtp_responses;
54
55 void smtp_close(struct query *ctl, int sayquit)
56 /* close the socket to SMTP server */
57 {
58     if (ctl->smtp_socket != -1)
59     {
60         if (sayquit)
61             SMTP_quit(ctl->smtp_socket, ctl->smtphostmode);
62         SockClose(ctl->smtp_socket);
63         ctl->smtp_socket = -1;
64     }
65     batchcount = 0;
66 }
67
68 int smtp_open(struct query *ctl)
69 /* try to open a socket to the appropriate SMTP server for this query */ 
70 {
71     /* maybe it's time to close the socket in order to force delivery */
72     if (last_smtp_ok > 0 && time((time_t *)NULL) - last_smtp_ok > mytimeout)
73     {
74         smtp_close(ctl, 1);
75         last_smtp_ok = 0;
76     }
77     if (NUM_NONZERO(ctl->batchlimit)) {
78         if (batchcount == ctl->batchlimit)
79             smtp_close(ctl, 1);
80         batchcount++;
81     }
82
83     /* if no socket to any SMTP host is already set up, try to open one */
84     if (ctl->smtp_socket == -1) 
85     {
86         /* 
87          * RFC 1123 requires that the domain name in HELO address is a
88          * "valid principal domain name" for the client host. If we're
89          * running in invisible mode, violate this with malice
90          * aforethought in order to make the Received headers and
91          * logging look right.
92          *
93          * In fact this code relies on the RFC1123 requirement that the
94          * SMTP listener must accept messages even if verification of the
95          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
96          *
97          * How we compute the true mailhost name to pass to the
98          * listener doesn't affect behavior on RFC1123-violating
99          * listeners that check for name match; we're going to lose
100          * on those anyway because we can never give them a name
101          * that matches the local machine fetchmail is running on.
102          * What it will affect is the listener's logging.
103          */
104         struct idlist   *idp;
105         const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
106         int oldphase = phase;
107         char *parsed_host = NULL;
108
109         errno = 0;
110
111         /*
112          * Run down the SMTP hunt list looking for a server that's up.
113          * Use both explicit hunt entries (value TRUE) and implicit 
114          * (default) ones (value FALSE).
115          */
116         oldphase = phase;
117         phase = LISTENER_WAIT;
118
119         set_timeout(ctl->server.timeout);
120         for (idp = ctl->smtphunt; idp; idp = idp->next)
121         {
122             char        *cp;
123             char        *portnum = SMTP_PORT;
124
125             ctl->smtphost = idp->id;  /* remember last host tried. */
126             if (ctl->smtphost[0]=='/')
127             {
128                 ctl->smtphostmode = LMTP_MODE;
129                 xfree(parsed_host);
130                 if ((ctl->smtp_socket = UnixOpen(ctl->smtphost))==-1)
131                     continue;
132             }
133             else
134             {
135                 ctl->smtphostmode = ctl->listener;
136                 parsed_host = xstrdup(idp->id);
137                 if ((cp = strrchr(parsed_host, '/')))
138                 {
139                     *cp++ = 0;
140                     if (cp[0])
141                         portnum = cp;
142                 }
143                 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,
144                                 ctl->server.plugout, &ai1)) == -1)
145                 {
146                     xfree(parsed_host);
147                     continue;
148                 }
149             }
150
151             /* return immediately for ODMR */
152             if (ctl->server.protocol == P_ODMR)
153             {
154                 set_timeout(0);
155                 phase = oldphase;
156                 xfree(parsed_host);
157                 return(ctl->smtp_socket); /* success */
158             }
159
160             /* first, probe for ESMTP */
161             if (SMTP_ok(ctl->smtp_socket, ctl->smtphostmode) == SM_OK &&
162                     SMTP_ehlo(ctl->smtp_socket, ctl->smtphostmode, id_me,
163                         ctl->server.esmtp_name, ctl->server.esmtp_password,
164                         &ctl->server.esmtp_options) == SM_OK)
165                 break;  /* success */
166
167             /*
168              * RFC 1869 warns that some listeners hang up on a failed EHLO,
169              * so it's safest not to assume the socket will still be good.
170              */
171             smtp_close(ctl, 0);
172
173             /* if opening for ESMTP failed, try SMTP */
174             if (ctl->smtphost[0]=='/')
175             {
176                 if ((ctl->smtp_socket = UnixOpen(ctl->smtphost))==-1)
177                     continue;
178             }
179             else
180             {
181                 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,
182                                 ctl->server.plugout, &ai1)) == -1)
183                 {
184                     xfree(parsed_host);
185                     continue;
186                 }
187             }
188
189             if (SMTP_ok(ctl->smtp_socket, ctl->smtphostmode) == SM_OK &&
190                     SMTP_helo(ctl->smtp_socket, ctl->smtphostmode, id_me) == SM_OK)
191                 break;  /* success */
192
193             smtp_close(ctl, 0);
194         }
195         set_timeout(0);
196         phase = oldphase;
197
198         /*
199          * RFC 1123 requires that the domain name part of the
200          * RCPT TO address be "canonicalized", that is a FQDN
201          * or MX but not a CNAME.  Some listeners (like exim)
202          * enforce this.  Now that we have the actual hostname,
203          * compute what we should canonicalize with.
204          */
205         xfree(ctl->destaddr);
206         if (ctl->smtpaddress)
207             ctl->destaddr = xstrdup(ctl->smtpaddress);
208         /* parsed_host is smtphost without the /port */
209         else if (parsed_host && parsed_host[0] != 0)
210             ctl->destaddr = xstrdup(parsed_host);
211         /* No smtphost is specified or it is a UNIX socket, then use
212            localhost as a domain part. */
213         else
214             ctl->destaddr = xstrdup("localhost");
215         xfree(parsed_host);
216     }
217     /* end if (ctl->smtp_socket == -1) */
218
219     if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
220         report(stdout, GT_("forwarding to %s\n"), ctl->smtphost);
221
222     return(ctl->smtp_socket);
223 }
224
225 static void sanitize(char *s)
226 /* replace ' by _ */
227 {
228     char *cp;
229
230     for (cp = s; (cp = strchr (cp, '\'')); cp++)
231         *cp = '_';
232 }
233
234 char *rcpt_address(struct query *ctl, const char *id,
235                           int usesmtpname)
236 {
237     static char addr[HOSTLEN+USERNAMELEN+1];
238     if (strchr(id, '@'))
239     {
240         snprintf(addr, sizeof (addr), "%s", id);
241     }
242     else if (usesmtpname && ctl->smtpname)
243     {
244         snprintf(addr, sizeof (addr), "%s", ctl->smtpname);
245     }
246     else
247     {
248         snprintf(addr, sizeof (addr), "%s@%s", id, ctl->destaddr);
249     }
250     return addr;
251 }
252
253 static int send_bouncemail(struct query *ctl, struct msgblk *msg,
254                            int userclass, char *message /* should have \r\n at the end */,
255                            int nerrors, char *errors[])
256 /* bounce back an error report a la RFC 1892 */
257 {
258     char daemon_name[15 + HOSTLEN] = "MAILER-DAEMON@";
259     char boundary[BUFSIZ], *bounce_to;
260     int sock;
261     static char *fqdn_of_host = NULL;
262     const char *md1 = "MAILER-DAEMON", *md2 = "MAILER-DAEMON@";
263
264     /* don't bounce in reply to undeliverable bounces */
265     if (!msg || !msg->return_path[0] ||
266         strcmp(msg->return_path, "<>") == 0 ||
267         strcasecmp(msg->return_path, md1) == 0 ||
268         strncasecmp(msg->return_path, md2, strlen(md2)) == 0)
269         return(TRUE);
270
271     bounce_to = (run.bouncemail ? msg->return_path : run.postmaster);
272
273     /* can't just use fetchmailhost here, it might be localhost */
274     if (fqdn_of_host == NULL)
275         fqdn_of_host = host_fqdn(0); /* can't afford to bail out and
276                                         lose the NDN here */
277     strlcat(daemon_name, fqdn_of_host, sizeof(daemon_name));
278
279     /* we need only SMTP for this purpose */
280     /* XXX FIXME: hardcoding localhost is nonsense if smtphost can be
281      * configured */
282     if ((sock = SockOpen("localhost", SMTP_PORT, NULL, &ai1)) == -1)
283         return(FALSE);
284
285     if (SMTP_ok(sock, SMTP_MODE) != SM_OK)
286     {
287         SockClose(sock);
288         return FALSE;
289     }
290
291     if (SMTP_helo(sock, SMTP_MODE, fetchmailhost) != SM_OK
292         || SMTP_from(sock, SMTP_MODE, "<>", (char *)NULL) != SM_OK
293         || SMTP_rcpt(sock, SMTP_MODE, bounce_to) != SM_OK
294         || SMTP_data(sock, SMTP_MODE) != SM_OK)
295     {
296         SMTP_quit(sock, SMTP_MODE);
297         SockClose(sock);
298         return(FALSE);
299     }
300
301     /* our first duty is to keep the sacred foo counters turning... */
302     snprintf(boundary, sizeof(boundary), "foo-mani-padme-hum-%ld-%ld-%ld", 
303             (long)getpid(), (long)getppid(), (long)time(NULL));
304
305     if (outlevel >= O_VERBOSE)
306         report(stdout, GT_("SMTP: (bounce-message body)\n"));
307     else
308         /* this will usually go to sylog... */
309         report(stderr, GT_("mail from %s bounced to %s\n"),
310                daemon_name, bounce_to);
311
312
313     /* bouncemail headers */
314     SockPrintf(sock, "Subject: Mail delivery failed: returning message to sender\r\n");
315     SockPrintf(sock, "From: Mail Delivery System <%s>\r\n", daemon_name);
316     SockPrintf(sock, "To: %s\r\n", bounce_to);
317     SockPrintf(sock, "MIME-Version: 1.0\r\n");
318     SockPrintf(sock, "Content-Type: multipart/report; report-type=delivery-status;\r\n\tboundary=\"%s\"\r\n", boundary);
319     SockPrintf(sock, "\r\n");
320
321     /* RFC1892 part 1 -- human-readable message */
322     SockPrintf(sock, "--%s\r\n", boundary); 
323     SockPrintf(sock,"Content-Type: text/plain\r\n");
324     SockPrintf(sock, "\r\n");
325     SockPrintf(sock, "This message was created automatically by mail delivery software.\r\n");
326     SockPrintf(sock, "\r\n");
327     SockPrintf(sock, "A message that you sent could not be delivered to one or more of its\r\n");
328     SockPrintf(sock, "recipients. This is a permanent error.\r\n");
329     SockPrintf(sock, "\r\n");
330     SockPrintf(sock, "Reason: %s", message);
331     SockPrintf(sock, "\r\n");
332     SockPrintf(sock, "The following address(es) failed:\r\n");
333
334     if (nerrors)
335     {
336         struct idlist   *idp;
337         int             nusers;
338         
339         nusers = 0;
340         for (idp = msg->recipients; idp; idp = idp->next)
341         {
342             if (idp->val.status.mark == userclass)
343             {
344                 char    *error;
345                 SockPrintf(sock, "%s\r\n", rcpt_address (ctl, idp->id, 1));
346                 
347                 if (nerrors == 1) error = errors[0];
348                 else if (nerrors <= nusers)
349                 {
350                     SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
351                     break;
352                 }
353                 else error = errors[nusers++];
354                         
355                 SockPrintf(sock, "   SMTP error: %s\r\n\r\n", error);
356             }
357         }
358     
359         /* RFC1892 part 2 -- machine-readable responses */
360         SockPrintf(sock, "--%s\r\n", boundary); 
361         SockPrintf(sock,"Content-Type: message/delivery-status\r\n");
362         SockPrintf(sock, "\r\n");
363         SockPrintf(sock, "Reporting-MTA: dns; %s\r\n", fqdn_of_host);
364
365         nusers = 0;
366         for (idp = msg->recipients; idp; idp = idp->next)
367             if (idp->val.status.mark == userclass)
368             {
369                 char    *error;
370                 /* Minimum RFC1894 compliance + Diagnostic-Code field */
371                 SockPrintf(sock, "\r\n");
372                 SockPrintf(sock, "Final-Recipient: rfc822; %s\r\n", 
373                            rcpt_address (ctl, idp->id, 1));
374                 SockPrintf(sock, "Last-Attempt-Date: %s\r\n", rfc822timestamp());
375                 SockPrintf(sock, "Action: failed\r\n");
376
377                 if (nerrors == 1)
378                     /* one error applies to all users */
379                     error = errors[0];
380                 else if (nerrors <= nusers)
381                 {
382                     SockPrintf(sock, "Internal error: SMTP error count doesn't match number of recipients.\r\n");
383                     break;
384                 }
385                 else
386                     /* errors correspond 1-1 to selected users */
387                     error = errors[nusers++];
388                 
389                 if (strlen(error) > 9 && isdigit((unsigned char)error[4])
390                         && error[5] == '.' && isdigit((unsigned char)error[6])
391                         && error[7] == '.' && isdigit((unsigned char)error[8]))
392                     /* Enhanced status code available, use it */
393                     SockPrintf(sock, "Status: %5.5s\r\n", &(error[4]));
394                 else
395                     /* Enhanced status code not available, fake one */
396                     SockPrintf(sock, "Status: %c.0.0\r\n", error[0]);
397                 SockPrintf(sock, "Diagnostic-Code: %s\r\n", error);
398             }
399         SockPrintf(sock, "\r\n");
400     }
401
402     /* RFC1892 part 3 -- headers of undelivered message */
403     SockPrintf(sock, "--%s\r\n", boundary); 
404     SockPrintf(sock, "Content-Type: text/rfc822-headers\r\n");
405     SockPrintf(sock, "\r\n");
406     if (msg->headers)
407     {
408         SockWrite(sock, msg->headers, strlen(msg->headers));
409         SockPrintf(sock, "\r\n");
410     }
411     SockPrintf(sock, "--%s--\r\n", boundary); 
412
413     if (SMTP_eom(sock, SMTP_MODE) != SM_OK
414             || SMTP_quit(sock, SMTP_MODE) != SM_OK)
415     {
416         SockClose(sock);
417         return(FALSE);
418     }
419
420     SockClose(sock);
421
422     return(TRUE);
423 }
424
425 static int handle_smtp_report(struct query *ctl, struct msgblk *msg)
426 /* handle SMTP errors based on the content of SMTP_response */
427 /* returns either PS_REFUSED (to delete message from the server),
428  *             or PS_TRANSIENT (keeps the message on the server) */
429 {
430     int smtperr = atoi(smtp_response);
431     char *responses[1];
432     struct idlist *walk;
433     int found = 0;
434
435     responses[0] = xstrdup(smtp_response);
436
437 #ifdef __UNUSED__
438     /*
439      * Don't do this!  It can really mess you up if, for example, you're
440      * reporting an error with a single RCPT TO address among several;
441      * RSET discards the message body and it doesn't get sent to the
442      * valid recipients.
443      */
444     SMTP_rset(ctl->smtp_socket);    /* stay on the safe side */
445     if (outlevel >= O_DEBUG)
446         report(stdout, GT_("Saved error is still %d\n"), smtperr);
447 #endif /* __UNUSED */
448
449     /*
450      * Note: send_bouncemail message strings are not made subject
451      * to gettext translation because (a) they're going to be 
452      * embedded in a text/plain 7bit part, and (b) they're
453      * going to be associated with listener error-response
454      * messages, which are probably in English (none of the
455      * MTAs I know about are internationalized).
456      */
457     for( walk = ctl->antispam; walk; walk = walk->next )
458         if ( walk->val.status.num == smtperr ) 
459         { 
460                 found=1;
461                 break;
462         }
463
464     /* if (str_find(&ctl->antispam, smtperr)) */
465     if ( found )
466     {
467         /*
468          * SMTP listener explicitly refuses to deliver mail
469          * coming from this address, probably due to an
470          * anti-spam domain exclusion.  Respect this.  Don't
471          * try to ship the message, and don't prevent it from
472          * being deleted.  There's no point in bouncing the
473          * email either since most spammers don't put their
474          * real return email address anywhere in the headers
475          * (unless the user insists with the SET SPAMBOUNCE
476          * config option).
477          *
478          * Default values:
479          *
480          * 571 = sendmail's "unsolicited email refused"
481          * 550 = exim's new antispam response (temporary)
482          * 501 = exim's old antispam response
483          * 554 = Postfix antispam response.
484          *
485          */
486         if (run.spambounce)
487         {
488             char rejmsg[160];
489             snprintf(rejmsg, sizeof(rejmsg),
490                     "spam filter or virus scanner rejected message because:\r\n"
491                     "%s\r\n", responses[0]);
492
493             send_bouncemail(ctl, msg, XMIT_ACCEPT,
494                     rejmsg, 1, responses);
495         }
496         free(responses[0]);
497         return(PS_REFUSED);
498     }
499
500     /*
501      * Suppress error message only if the response specifically 
502      * meant `excluded for policy reasons'.  We *should* see
503      * an error when the return code is less specific.
504      */
505     if (smtperr >= 400)
506         report(stderr, GT_("%cMTP error: %s\n"), 
507               ctl->smtphostmode,
508               responses[0]);
509
510     switch (smtperr)
511     {
512     case 552: /* message exceeds fixed maximum message size */
513         /*
514          * Permanent no-go condition on the
515          * ESMTP server.  Don't try to ship the message, 
516          * and allow it to be deleted.
517          */
518         if (run.bouncemail)
519             send_bouncemail(ctl, msg, XMIT_ACCEPT,
520                         "This message was too large (SMTP error 552).\r\n", 
521                         1, responses);
522         free(responses[0]);
523         return(PS_REFUSED);
524   
525     case 553: /* invalid sending domain */
526         /*
527          * These latter days 553 usually means a spammer is trying to
528          * cover his tracks.  We never bouncemail on these, because 
529          * (a) the return address is invalid by definition, and 
530          * (b) we wouldn't want spammers to get confirmation that
531          * this address is live, anyway.
532          */
533 #ifdef __DONT_FEED_THE_SPAMMERS__
534         if (run.bouncemail)
535             send_bouncemail(ctl, msg, XMIT_ACCEPT,
536                         "Invalid address in MAIL FROM (SMTP error 553).\r\n", 
537                         1, responses);
538 #endif /* __DONT_FEED_THE_SPAMMERS__ */
539         free(responses[0]);
540         return(PS_REFUSED);
541
542     default:
543         /* bounce non-transient errors back to the sender */
544         if (smtperr >= 500 && smtperr <= 599)
545         {
546             if (run.bouncemail)
547                 send_bouncemail(ctl, msg, XMIT_ACCEPT,
548                                 "General SMTP/ESMTP error.\r\n", 
549                                 1, responses);
550             free(responses[0]);
551             return(PS_REFUSED);
552         }
553         /*
554          * We're going to end up here on 4xx errors, like:
555          *
556          * 451: temporarily unable to identify sender (exim)
557          * 452: temporary out-of-queue-space condition on the ESMTP server.
558          *
559          * These are temporary errors.  Don't try to ship the message,
560          * and suppress deletion so it can be retried on a future
561          * retrieval cycle.
562          *
563          * Bouncemail *might* be appropriate here as a delay
564          * notification (note; if we ever add this, we must make
565          * sure the RFC1894 Action field is "delayed" rather than
566          * "failed").  But it's not really necessary because
567          * these are not actual failures, we're very likely to be
568          * able to recover on the next cycle.
569          */
570         free(responses[0]);
571         return(PS_TRANSIENT);
572     }
573 }
574
575 static int handle_smtp_report_without_bounce(struct query *ctl, struct msgblk *msg)
576 /* handle SMTP errors based on the content of SMTP_response */
577 /* atleast one PS_TRANSIENT: do not send the bounce mail, keep the mail;
578  * no PS_TRANSIENT, atleast one PS_SUCCESS: send the bounce mail, delete the mail;
579  * no PS_TRANSIENT, no PS_SUCCESS: do not send the bounce mail, delete the mail */
580 {
581     int smtperr = atoi(smtp_response);
582
583     if (str_find(&ctl->antispam, smtperr))
584     {
585         if (run.spambounce)
586          return(PS_SUCCESS);
587         return(PS_REFUSED);
588     }
589
590     if (smtperr >= 400)
591         report(stderr, GT_("%cMTP error: %s\n"), 
592               ctl->smtphostmode,
593               smtp_response);
594
595     switch (smtperr)
596     {
597     case 552: /* message exceeds fixed maximum message size */
598         if (run.bouncemail)
599             return(PS_SUCCESS);
600         return(PS_REFUSED);
601
602     case 553: /* invalid sending domain */
603 #ifdef __DONT_FEED_THE_SPAMMERS__
604         if (run.bouncemail)
605             return(PS_SUCCESS);
606 #endif /* __DONT_FEED_THE_SPAMMERS__ */
607         return(PS_REFUSED);
608
609     default:
610         /* bounce non-transient errors back to the sender */
611         if (smtperr >= 500 && smtperr <= 599)
612             return(PS_SUCCESS);
613         return(PS_TRANSIENT);
614     }
615 }
616
617 /* these are shared by open_sink and stuffline */
618 static FILE *sinkfp;
619
620 int stuffline(struct query *ctl, char *buf)
621 /* ship a line to the given control block's output sink (SMTP server or MDA) */
622 {
623     int n, oldphase;
624     char *last;
625
626     /* The line may contain NUL characters. Find the last char to use
627      * -- the real line termination is the sequence "\n\0".
628      */
629     last = buf + 1; /* last[-1] must be valid! */
630     while ((last += strlen(last)) && (last[-1] != '\n'))
631         last++;
632
633     /* fix message lines that have only \n termination (for qmail) */
634     if (ctl->forcecr)
635     {
636         if (last - 1 == buf || last[-2] != '\r')
637         {
638             last[-1] = '\r';
639             *last++  = '\n';
640             *last    = '\0';
641         }
642     }
643
644     oldphase = phase;
645     phase = FORWARDING_WAIT;
646
647     /*
648      * SMTP byte-stuffing.  We only do this if the protocol does *not*
649      * use .<CR><LF> as EOM.  If it does, the server will already have
650      * decorated any . lines it sends back up.
651      */
652     if (*buf == '.')
653     {
654         if (ctl->server.base_protocol->delimited)       /* server has already byte-stuffed */
655         {
656             if (ctl->mda) {
657                 /* writing to MDA, undo byte-stuffing */
658                 ++buf;
659             } else {
660                 /* writing to SMTP, leave the byte-stuffing in place */;
661             }
662         }
663         else /* if (!protocol->delimited)       -- not byte-stuffed already */
664         {
665             /* byte-stuff it */
666             if (!ctl->mda)  {
667                 if (!ctl->bsmtp) {
668                     n = SockWrite(ctl->smtp_socket, buf, 1);
669                 } else {
670                     n = fwrite(buf, 1, 1, sinkfp);
671                     if (ferror(sinkfp)) n = -1;
672                 }
673                 if (n < 0)
674                     return n;
675             }
676         }
677     }
678
679     /* we may need to strip carriage returns */
680     if (ctl->stripcr)
681     {
682         char    *sp, *tp;
683
684         for (sp = tp = buf; sp < last; sp++)
685             if (*sp != '\r')
686                 *tp++ =  *sp;
687         *tp = '\0';
688         last = tp;
689     }
690
691     n = 0;
692     if (ctl->mda || ctl->bsmtp) {
693         n = fwrite(buf, 1, last - buf, sinkfp);
694         if (ferror(sinkfp)) n = -1;
695     } else if (ctl->smtp_socket != -1)
696         n = SockWrite(ctl->smtp_socket, buf, last - buf);
697
698     phase = oldphase;
699
700     return(n);
701 }
702
703 static int open_bsmtp_sink(struct query *ctl, struct msgblk *msg,
704               int *good_addresses, int *bad_addresses)
705 /* open a BSMTP stream */
706 {
707     struct      idlist *idp;
708     int         need_anglebrs;
709
710     if (strcmp(ctl->bsmtp, "-") == 0)
711         sinkfp = stdout;
712     else
713         sinkfp = fopen(ctl->bsmtp, "a");
714
715     if (!sinkfp || ferror(sinkfp)) {
716         report(stderr, GT_("BSMTP file open failed: %s\n"), 
717                 strerror(errno));
718         return(PS_BSMTP);
719     }
720
721     /* see the ap computation under the SMTP branch */
722     need_anglebrs = (msg->return_path[0] != '<');
723     fprintf(sinkfp,
724             "MAIL FROM:%s%s%s",
725             need_anglebrs ? "<" : "",
726             (msg->return_path[0]) ? msg->return_path : user,
727             need_anglebrs ? ">" : "");
728
729     if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
730         fputs(" BODY=8BITMIME", sinkfp);
731     else if (ctl->mimemsg & MSG_IS_7BIT)
732         fputs(" BODY=7BIT", sinkfp);
733
734     /* exim's BSMTP processor does not handle SIZE */
735     /* fprintf(sinkfp, " SIZE=%d", msg->reallen); */
736
737     fprintf(sinkfp, "\r\n");
738
739     /*
740      * RFC 1123 requires that the domain name part of the
741      * RCPT TO address be "canonicalized", that is a FQDN
742      * or MX but not a CNAME.  Some listeners (like exim)
743      * enforce this.  Now that we have the actual hostname,
744      * compute what we should canonicalize with.
745      */
746     xfree(ctl->destaddr);
747     ctl->destaddr = xstrdup(ctl->smtpaddress ? ctl->smtpaddress : "localhost");
748
749     *bad_addresses = 0;
750     for (idp = msg->recipients; idp; idp = idp->next)
751         if (idp->val.status.mark == XMIT_ACCEPT)
752         {
753             fprintf(sinkfp, "RCPT TO:<%s>\r\n",
754                 rcpt_address (ctl, idp->id, 1));
755             (*good_addresses)++;
756         }
757
758     fputs("DATA\r\n", sinkfp);
759
760     if (fflush(sinkfp) || ferror(sinkfp))
761     {
762         report(stderr, GT_("BSMTP preamble write failed.\n"));
763         return(PS_BSMTP);
764     }
765
766     return(PS_SUCCESS);
767 }
768
769 /* this is experimental and will be removed if double bounces are reported */
770 #define EXPLICIT_BOUNCE_ON_BAD_ADDRESS
771
772
773 static const char *is_quad(const char *q)
774 /* Check if the string passed in points to what could be one quad of a
775  * dotted-quad IP address.  Requirements are that the string is not a
776  * NULL pointer, begins with a period (which is skipped) or a digit
777  * and ends with a period or a NULL.  If these requirements are met, a
778  * pointer to the last character (the period or the NULL character) is
779  * returned; otherwise NULL.
780  */
781 {
782   const char *r;
783   
784   if (!q || !*q)
785     return NULL;
786   if (*q == '.')
787     q++;
788   for(r=q;isdigit((unsigned char)*r);r++)
789     ;
790   if ( ((*r) && (*r != '.')) || ((r-q) < 1) || ((r-q)>3) )
791     return NULL;
792   /* Make sure quad is < 255 */
793   if ( (r-q) == 3)
794   {
795     if (*q > '2')
796       return NULL;
797     else if (*q == '2')
798     {
799       if (*(q+1) > '5')
800         return NULL;
801       else if (*(q+1) == '5')
802       {
803         if (*(q+2) > '5')
804           return NULL;
805       }
806     }
807   }
808   return r;
809 }
810
811 static int is_dottedquad(const char *hostname)
812 /* Returns a true value if the passed in string looks like an IP
813  *  address in dotted-quad form, and a false value otherwise.
814  */
815
816 {
817   return ((hostname=is_quad(is_quad(is_quad(is_quad(hostname))))) != NULL) &&
818     (*hostname == '\0');
819 }
820
821 static int open_smtp_sink(struct query *ctl, struct msgblk *msg,
822               int *good_addresses, int *bad_addresses /* this must be signed, to prevent endless loop in from_addresses */)
823 /* open an SMTP stream */
824 {
825     const char  *ap;
826     struct      idlist *idp;
827     char                options[MSGBUFSIZE]; 
828     char                addr[HOSTLEN+USERNAMELEN+1];
829 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
830     char                **from_responses;
831 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
832     int         total_addresses;
833     int         force_transient_error = 0;
834     int         smtp_err;
835
836     /*
837      * Compute ESMTP options.
838      */
839     options[0] = '\0';
840     if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
841          if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
842             strcpy(options, " BODY=8BITMIME");
843          else if (ctl->mimemsg & MSG_IS_7BIT)
844             strcpy(options, " BODY=7BIT");
845     }
846
847     if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
848         sprintf(options + strlen(options), " SIZE=%d", msg->reallen);
849
850     /*
851      * Try to get the SMTP listener to take the Return-Path
852      * address as MAIL FROM.  If it won't, fall back on the
853      * remotename and mailserver host.  This won't affect replies,
854      * which use the header From address anyway; the MAIL FROM
855      * address is a place for the SMTP listener to send
856      * bouncemail.  The point is to guarantee a FQDN in the MAIL
857      * FROM line -- some SMTP listeners, like smail, become
858      * unhappy otherwise.
859      *
860      * RFC 1123 requires that the domain name part of the
861      * MAIL FROM address be "canonicalized", that is a
862      * FQDN or MX but not a CNAME.  We'll assume the Return-Path
863      * header is already in this form here (it certainly
864      * is if rewrite is on).  RFC 1123 is silent on whether
865      * a nonexistent hostname part is considered canonical.
866      *
867      * This is a potential problem if the MTAs further upstream
868      * didn't pass canonicalized From/Return-Path lines, *and* the
869      * local SMTP listener insists on them. 
870      *
871      * Handle the case where an upstream MTA is setting a return
872      * path equal to "@".  Ghod knows why anyone does this, but 
873      * it's been reported to happen in mail from Amazon.com and
874      * Motorola.
875      *
876      * Also, if the hostname is a dotted quad, wrap it in square brackets.
877      * Apparently this is required by RFC2821, section 4.1.3.
878      */
879     if (!msg->return_path[0] || (msg->return_path[0] == '@'))
880     {
881       if (strchr(ctl->remotename,'@') || strchr(ctl->remotename,'!'))
882       {
883         snprintf(addr, sizeof(addr), "%s", ctl->remotename);
884       }
885       else if (is_dottedquad(ctl->server.truename))
886       {
887         snprintf(addr, sizeof(addr), "%s@[%s]", ctl->remotename,
888                 ctl->server.truename);
889       }
890       else
891       {
892         snprintf(addr, sizeof(addr),
893               "%s@%s", ctl->remotename, ctl->server.truename);
894       }
895         ap = addr;
896     }
897     else if (strchr(msg->return_path,'@') || strchr(msg->return_path,'!'))
898         ap = msg->return_path;
899     /* in case Return-Path was "<>" we want to preserve that */
900     else if (strcmp(msg->return_path,"<>") == 0)
901         ap = msg->return_path;
902     else                /* in case Return-Path existed but was local */
903     {
904       if (is_dottedquad(ctl->server.truename))
905       {
906         snprintf(addr, sizeof(addr), "%s@[%s]", msg->return_path,
907                 ctl->server.truename);
908       }
909       else
910       {
911         snprintf(addr, sizeof(addr), "%s@%s",
912                 msg->return_path, ctl->server.truename);
913       }
914         ap = addr;
915     }
916
917     if ((smtp_err = SMTP_from(ctl->smtp_socket, ctl->smtphostmode,
918                     ap, options)) == SM_UNRECOVERABLE)
919     {
920         smtp_close(ctl, 0);
921         return(PS_TRANSIENT);
922     }
923     if (smtp_err != SM_OK)
924     {
925         int err = handle_smtp_report(ctl, msg); /* map to PS_TRANSIENT or PS_REFUSED */
926
927         SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);    /* stay on the safe side */
928         return(err);
929     }
930
931     /*
932      * Now list the recipient addressees
933      */
934     total_addresses = 0;
935     for (idp = msg->recipients; idp; idp = idp->next)
936         total_addresses++;
937 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
938     from_responses = (char **)xmalloc(sizeof(char *) * total_addresses);
939 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
940     for (idp = msg->recipients; idp; idp = idp->next)
941         if (idp->val.status.mark == XMIT_ACCEPT)
942         {
943             const char *address;
944             address = rcpt_address (ctl, idp->id, 1);
945             if ((smtp_err = SMTP_rcpt(ctl->smtp_socket, ctl->smtphostmode,
946                             address)) == SM_UNRECOVERABLE)
947             {
948                 smtp_close(ctl, 0);
949 transient:
950 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
951                 while (*bad_addresses)
952                     free(from_responses[--*bad_addresses]);
953                 free(from_responses);
954 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
955                 return(PS_TRANSIENT);
956             }
957             if (smtp_err == SM_OK)
958                 (*good_addresses)++;
959             else
960             {
961                 switch (handle_smtp_report_without_bounce(ctl, msg))
962                 {
963                     case PS_TRANSIENT:
964                     force_transient_error = 1;
965                     break;
966
967                     case PS_SUCCESS:
968 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
969                     from_responses[*bad_addresses] = xstrdup(smtp_response);
970 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
971
972                     (*bad_addresses)++;
973                     idp->val.status.mark = XMIT_RCPTBAD;
974                     if (outlevel >= O_VERBOSE)
975                         report(stderr,
976                               GT_("%cMTP listener doesn't like recipient address `%s'\n"),
977                               ctl->smtphostmode, address);
978                     break;
979
980                     case PS_REFUSED:
981                     if (outlevel >= O_VERBOSE)
982                         report(stderr,
983                               GT_("%cMTP listener doesn't really like recipient address `%s'\n"),
984                               ctl->smtphostmode, address);
985                     break;
986                 }
987             }
988         }
989
990     if (force_transient_error) {
991             /* do not risk dataloss due to overengineered multidrop
992              * crap. If one of the recipients returned PS_TRANSIENT,
993              * we return exactly that.
994              */
995             SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);        /* required by RFC1870 */
996             goto transient;
997     }
998 #ifdef EXPLICIT_BOUNCE_ON_BAD_ADDRESS
999     /*
1000      * This should not be necessary, because the SMTP listener itself
1001      * should generate a bounce for the bad address.
1002      *
1003      * XXX FIXME 2006-01-19: is this comment true? I don't think
1004      * it is, because the SMTP listener isn't required to accept bogus
1005      * messages. There appears to be general SMTP<->MDA and
1006      * responsibility confusion.
1007      */
1008     if (*bad_addresses)
1009         send_bouncemail(ctl, msg, XMIT_RCPTBAD,
1010                         "Some addresses were rejected by the MDA fetchmail forwards to.\r\n",
1011                         *bad_addresses, from_responses);
1012     while (*bad_addresses)
1013         free(from_responses[--*bad_addresses]);
1014     free(from_responses);
1015 #endif /* EXPLICIT_BOUNCE_ON_BAD_ADDRESS */
1016
1017     /*
1018      * It's tempting to do local notification only if bouncemail was
1019      * insufficient -- that is, to add && total_addresses > *bad_addresses
1020      * to the test here.  The problem with this theory is that it would
1021      * make initial diagnosis of a broken multidrop configuration very
1022      * hard -- most single-recipient messages would just invisibly bounce.
1023      */
1024     if (!(*good_addresses)) 
1025     {
1026         if (!run.postmaster[0])
1027         {
1028             if (outlevel >= O_VERBOSE)
1029                 report(stderr, GT_("no address matches; no postmaster set.\n"));
1030             SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);     /* required by RFC1870 */
1031             return(PS_REFUSED);
1032         }
1033         if ((smtp_err = SMTP_rcpt(ctl->smtp_socket, ctl->smtphostmode,
1034                 rcpt_address (ctl, run.postmaster, 0))) == SM_UNRECOVERABLE)
1035         {
1036             smtp_close(ctl, 0);
1037             return(PS_TRANSIENT);
1038         }
1039         if (smtp_err != SM_OK)
1040         {
1041             report(stderr, GT_("can't even send to %s!\n"), run.postmaster);
1042             SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);     /* required by RFC1870 */
1043             return(PS_REFUSED);
1044         }
1045
1046         if (outlevel >= O_VERBOSE)
1047             report(stderr, GT_("no address matches; forwarding to %s.\n"), run.postmaster);
1048     }
1049
1050     /* 
1051      * Tell the listener we're ready to send data.
1052      * Some listeners (like zmailer) may return antispam errors here.
1053      */
1054     if ((smtp_err = SMTP_data(ctl->smtp_socket, ctl->smtphostmode))
1055             == SM_UNRECOVERABLE)
1056     {
1057         smtp_close(ctl, 0);
1058         return(PS_TRANSIENT);
1059     }
1060     if (smtp_err != SM_OK)
1061     {
1062         int err = handle_smtp_report(ctl, msg);
1063         SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);    /* stay on the safe side */
1064         return(err);
1065     }
1066
1067     /*
1068      * We need to stash this away in order to know how many
1069      * response lines to expect after the LMTP end-of-message.
1070      */
1071     lmtp_responses = *good_addresses;
1072
1073     return(PS_SUCCESS);
1074 }
1075
1076 static int open_mda_sink(struct query *ctl, struct msgblk *msg,
1077               int *good_addresses, int *bad_addresses)
1078 /* open a stream to a local MDA */
1079 {
1080 #ifdef HAVE_SETEUID
1081     uid_t orig_uid;
1082 #endif /* HAVE_SETEUID */
1083     struct      idlist *idp;
1084     int length = 0, fromlen = 0, nameslen = 0;
1085     char        *names = NULL, *before, *after, *from = NULL;
1086
1087     (void)bad_addresses;
1088     xfree(ctl->destaddr);
1089     ctl->destaddr = xstrdup("localhost");
1090
1091     for (idp = msg->recipients; idp; idp = idp->next)
1092         if (idp->val.status.mark == XMIT_ACCEPT)
1093             (*good_addresses)++;
1094
1095     length = strlen(ctl->mda);
1096     before = xstrdup(ctl->mda);
1097
1098     /* get user addresses for %T (or %s for backward compatibility) */
1099     if (strstr(before, "%s") || strstr(before, "%T"))
1100     {
1101         /*
1102          * We go through this in order to be able to handle very
1103          * long lists of users and (re)implement %s.
1104          */
1105         nameslen = 0;
1106         for (idp = msg->recipients; idp; idp = idp->next)
1107             if ((idp->val.status.mark == XMIT_ACCEPT))
1108                 nameslen += (strlen(idp->id) + 1);      /* string + ' ' */
1109         if ((*good_addresses == 0))
1110             nameslen = strlen(run.postmaster);
1111
1112         names = (char *)xmalloc(nameslen + 1);  /* account for '\0' */
1113         if (*good_addresses == 0)
1114             strcpy(names, run.postmaster);
1115         else
1116         {
1117             names[0] = '\0';
1118             for (idp = msg->recipients; idp; idp = idp->next)
1119                 if (idp->val.status.mark == XMIT_ACCEPT)
1120                 {
1121                     strcat(names, idp->id);
1122                     strcat(names, " ");
1123                 }
1124             names[--nameslen] = '\0';   /* chop trailing space */
1125         }
1126
1127         sanitize(names);
1128     }
1129
1130     /* get From address for %F */
1131     if (strstr(before, "%F"))
1132     {
1133         from = xstrdup(msg->return_path);
1134
1135         sanitize(from);
1136
1137         fromlen = strlen(from);
1138     }
1139
1140     /* do we have to build an mda string? */
1141     if (names || from) 
1142     {           
1143         char    *sp, *dp;
1144
1145         /* find length of resulting mda string */
1146         sp = before;
1147         while ((sp = strstr(sp, "%s"))) {
1148             length += nameslen; /* subtract %s and add '' */
1149             sp += 2;
1150         }
1151         sp = before;
1152         while ((sp = strstr(sp, "%T"))) {
1153             length += nameslen; /* subtract %T and add '' */
1154             sp += 2;
1155         }
1156         sp = before;
1157         while ((sp = strstr(sp, "%F"))) {
1158             length += fromlen;  /* subtract %F and add '' */
1159             sp += 2;
1160         }
1161
1162         after = (char *)xmalloc(length + 1);
1163
1164         /* copy mda source string to after, while expanding %[sTF] */
1165         for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
1166             if (sp[0] != '%')   continue;
1167
1168             /* need to expand? BTW, no here overflow, because in
1169             ** the worst case (end of string) sp[1] == '\0' */
1170             if (sp[1] == 's' || sp[1] == 'T') {
1171                 *dp++ = '\'';
1172                 strcpy(dp, names);
1173                 dp += nameslen;
1174                 *dp++ = '\'';
1175                 sp++;   /* position sp over [sT] */
1176                 dp--;   /* adjust dp */
1177             } else if (sp[1] == 'F') {
1178                 *dp++ = '\'';
1179                 strcpy(dp, from);
1180                 dp += fromlen;
1181                 *dp++ = '\'';
1182                 sp++;   /* position sp over F */
1183                 dp--;   /* adjust dp */
1184             }
1185         }
1186
1187         if (names) {
1188             free(names);
1189             names = NULL;
1190         }
1191         if (from) {
1192             free(from);
1193             from = NULL;
1194         }
1195
1196         free(before);
1197
1198         before = after;
1199     }
1200
1201
1202     if (outlevel >= O_DEBUG)
1203         report(stdout, GT_("about to deliver with: %s\n"), before);
1204
1205 #ifdef HAVE_SETEUID
1206     /*
1207      * Arrange to run with user's permissions if we're root.
1208      * This will initialize the ownership of any files the
1209      * MDA creates properly.  (The seteuid call is available
1210      * under all BSDs and Linux)
1211      */
1212     orig_uid = getuid();
1213     seteuid(ctl->uid);
1214 #endif /* HAVE_SETEUID */
1215
1216     sinkfp = popen(before, "w");
1217     free(before);
1218     before = NULL;
1219
1220 #ifdef HAVE_SETEUID
1221     /* this will fail quietly if we didn't start as root */
1222     seteuid(orig_uid);
1223 #endif /* HAVE_SETEUID */
1224
1225     if (!sinkfp)
1226     {
1227         report(stderr, GT_("MDA open failed\n"));
1228         return(PS_IOERR);
1229     }
1230
1231     /*
1232      * We need to disable the normal SIGCHLD handling here because 
1233      * sigchld_handler() would reap away the error status, returning
1234      * error status instead of 0 for successful completion.
1235      */
1236     set_signal_handler(SIGCHLD, SIG_DFL);
1237
1238     return(PS_SUCCESS);
1239 }
1240
1241 int open_sink(struct query *ctl, struct msgblk *msg,
1242               int *good_addresses, int *bad_addresses)
1243 /* set up sinkfp to be an input sink we can ship a message to */
1244 {
1245     *bad_addresses = *good_addresses = 0;
1246
1247     if (ctl->bsmtp)             /* dump to a BSMTP batch file */
1248         return(open_bsmtp_sink(ctl, msg, good_addresses, bad_addresses));
1249     /* 
1250      * Try to forward to an SMTP or LMTP listener.  If the attempt to 
1251      * open a socket fails, fall through to attempt delivery via
1252      * local MDA.
1253      */
1254     else if (!ctl->mda && smtp_open(ctl) != -1)
1255         return(open_smtp_sink(ctl, msg, good_addresses, bad_addresses));
1256
1257     /*
1258      * Awkward case.  User didn't specify an MDA.  Our attempt to get a
1259      * listener socket failed.  Try to cope anyway -- initial configuration
1260      * may have found procmail.
1261      */
1262     else if (!ctl->mda)
1263     {
1264         report(stderr, GT_("%cMTP connect to %s failed\n"),
1265                ctl->smtphostmode,
1266                ctl->smtphost ? ctl->smtphost : "localhost");
1267
1268 #ifndef FALLBACK_MDA
1269         /* No fallback MDA declared.  Bail out. */
1270         return(PS_SMTP);
1271 #else
1272         /*
1273          * If user had things set up to forward offsite, no way
1274          * we want to deliver locally!
1275          */
1276         if (ctl->smtphost && strcmp(ctl->smtphost, "localhost"))
1277             return(PS_SMTP);
1278
1279         /* 
1280          * User was delivering locally.  We have a fallback MDA.
1281          * Latch it in place, logging the error, and fall through.
1282          * Set stripcr as we would if MDA had been the initial transport
1283          */
1284         ctl->mda = FALLBACK_MDA;
1285         if (!ctl->forcecr)
1286             ctl->stripcr = TRUE;
1287
1288         report(stderr, GT_("can't raise the listener; falling back to %s"),
1289                          FALLBACK_MDA);
1290 #endif
1291     }
1292
1293     if (ctl->mda)               /* must deliver through an MDA */
1294         return(open_mda_sink(ctl, msg, good_addresses, bad_addresses));
1295
1296     return(PS_SUCCESS);
1297 }
1298
1299 void release_sink(struct query *ctl)
1300 /* release the per-message output sink, whether it's a pipe or SMTP socket */
1301 {
1302     if (ctl->bsmtp && sinkfp)
1303     {
1304         if (strcmp(ctl->bsmtp, "-"))
1305         {
1306             fclose(sinkfp);
1307             sinkfp = (FILE *)NULL;
1308         }
1309     }
1310     else if (ctl->mda)
1311     {
1312         if (sinkfp)
1313         {
1314             pclose(sinkfp);
1315             sinkfp = (FILE *)NULL;
1316         }
1317         deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1318     }
1319 }
1320
1321 int close_sink(struct query *ctl, struct msgblk *msg, flag forward)
1322 /* perform end-of-message actions on the current output sink */
1323 {
1324     int smtp_err;
1325     if (ctl->mda)
1326     {
1327         int rc = 0, e = 0, e2 = 0, err = 0;
1328
1329         /* close the delivery pipe, we'll reopen before next message */
1330         if (sinkfp)
1331         {
1332             if (ferror(sinkfp))
1333                 err = 1, e2 = errno;
1334             if ((fflush(sinkfp)))
1335                 err = 1, e2 = errno;
1336
1337             errno = 0;
1338             rc = pclose(sinkfp);
1339             e = errno;
1340             sinkfp = (FILE *)NULL;
1341         }
1342         else
1343             rc = e = 0;
1344
1345         deal_with_sigchld(); /* Restore SIGCHLD handling to reap zombies */
1346
1347         if (rc || err)
1348         {
1349             if (err) {
1350                 report(stderr, GT_("Error writing to MDA: %s\n"), strerror(e2));
1351             } else if (WIFSIGNALED(rc)) {
1352                 report(stderr, 
1353                         GT_("MDA died of signal %d\n"), WTERMSIG(rc));
1354             } else if (WIFEXITED(rc)) {
1355                 report(stderr, 
1356                         GT_("MDA returned nonzero status %d\n"), WEXITSTATUS(rc));
1357             } else {
1358                 report(stderr,
1359                         GT_("Strange: MDA pclose returned %d and errno %d/%s, cannot handle at %s:%d\n"),
1360                         rc, e, strerror(e), __FILE__, __LINE__);
1361             }
1362
1363             return(FALSE);
1364         }
1365     }
1366     else if (ctl->bsmtp && sinkfp)
1367     {
1368         int error;
1369
1370         /* implicit disk-full check here... */
1371         fputs(".\r\n", sinkfp);
1372         error = ferror(sinkfp);
1373         if (strcmp(ctl->bsmtp, "-"))
1374         {
1375             if (fclose(sinkfp) == EOF) error = 1;
1376             sinkfp = (FILE *)NULL;
1377         }
1378         if (error)
1379         {
1380             report(stderr, 
1381                    GT_("Message termination or close of BSMTP file failed\n"));
1382             return(FALSE);
1383         }
1384     }
1385     else if (forward)
1386     {
1387         /* write message terminator */
1388         if ((smtp_err = SMTP_eom(ctl->smtp_socket, ctl->smtphostmode))
1389                 == SM_UNRECOVERABLE)
1390         {
1391             smtp_close(ctl, 0);
1392             return(FALSE);
1393         }
1394         if (smtp_err != SM_OK)
1395         {
1396             if (handle_smtp_report(ctl, msg) != PS_REFUSED)
1397             {
1398                 SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);    /* stay on the safe side */
1399                 return(FALSE);
1400             }
1401             else
1402             {
1403                 report(stderr, GT_("SMTP listener refused delivery\n"));
1404                 SMTP_rset(ctl->smtp_socket, ctl->smtphostmode);    /* stay on the safe side */
1405                 return(TRUE);
1406             }
1407         }
1408
1409         /*
1410          * If this is an SMTP connection, SMTP_eom() ate the response.
1411          * But could be this is an LMTP connection, in which case we have to
1412          * interpret either (a) a single 503 response meaning there
1413          * were no successful RCPT TOs, or (b) a variable number of
1414          * responses, one for each successful RCPT TO.  We need to send
1415          * bouncemail on each failed response and then return TRUE anyway,
1416          * otherwise the message will get left in the queue and resent
1417          * to people who got it the first time.
1418          */
1419         if (ctl->smtphostmode == LMTP_MODE)
1420         {
1421             if (lmtp_responses == 0)
1422             {
1423                 SMTP_ok(ctl->smtp_socket, ctl->smtphostmode);
1424
1425                 /*
1426                  * According to RFC2033, 503 is the only legal response
1427                  * if no RCPT TO commands succeeded.  No error recovery
1428                  * is really possible here, as we have no idea what
1429                  * insane thing the listener might be doing if it doesn't
1430                  * comply.
1431                  */
1432                 if (atoi(smtp_response) == 503)
1433                     report(stderr, GT_("LMTP delivery error on EOM\n"));
1434                 else
1435                     report(stderr,
1436                           GT_("Unexpected non-503 response to LMTP EOM: %s\n"),
1437                           smtp_response);
1438
1439                 /*
1440                  * It's not completely clear what to do here.  We choose to
1441                  * interpret delivery failure here as a transient error, 
1442                  * the same way SMTP delivery failure is handled.  If we're
1443                  * wrong, an undead message will get stuck in the queue.
1444                  */
1445                 return(FALSE);
1446             }
1447             else
1448             {
1449                 int     i, errors, rc = FALSE;
1450                 char    **responses;
1451
1452                 /* eat the RFC2033-required responses, saving errors */ 
1453                 responses = (char **)xmalloc(sizeof(char *) * lmtp_responses);
1454                 for (errors = i = 0; i < lmtp_responses; i++)
1455                 {
1456                     if ((smtp_err = SMTP_ok(ctl->smtp_socket, ctl->smtphostmode))
1457                             == SM_UNRECOVERABLE)
1458                     {
1459                         smtp_close(ctl, 0);
1460                         goto unrecov;
1461                     }
1462                     if (smtp_err != SM_OK)
1463                     {
1464                         responses[errors] = xstrdup(smtp_response);
1465                         errors++;
1466                     }
1467                 }
1468
1469                 if (errors == 0)
1470                     rc = TRUE;  /* all deliveries succeeded */
1471                 else
1472                     /*
1473                      * One or more deliveries failed.
1474                      * If we can bounce a failures list back to the
1475                      * sender, and the postmaster does not want to
1476                      * deal with the bounces return TRUE, deleting the
1477                      * message from the server so it won't be
1478                      * re-forwarded on subsequent poll cycles.
1479                      */
1480                     rc = send_bouncemail(ctl, msg, XMIT_ACCEPT,
1481                             "LMTP partial delivery failure.\r\n",
1482                             errors, responses);
1483
1484 unrecov:
1485                 for (i = 0; i < errors; i++)
1486                     free(responses[i]);
1487                 free(responses);
1488                 return rc;
1489             }
1490         }
1491     }
1492
1493     return(TRUE);
1494 }
1495
1496 int open_warning_by_mail(struct query *ctl)
1497 /* set up output sink for a mailed warning to calling user */
1498 {
1499     int good, bad;
1500
1501     /*
1502      * Dispatching warning email is a little complicated.  The problem is
1503      * that we have to deal with three distinct cases:
1504      *
1505      * 1. Single-drop running from user account.  Warning mail should
1506      * go to the local name for which we're collecting (coincides
1507      * with calling user).
1508      *
1509      * 2. Single-drop running from root or other privileged ID, with rc
1510      * file generated on the fly (Ken Estes's weird setup...)  Mail
1511      * should go to the local name for which we're collecting (does not 
1512      * coincide with calling user).
1513      * 
1514      * 3. Multidrop.  Mail must go to postmaster.  We leave the recipients
1515      * member null so this message will fall through to run.postmaster.
1516      *
1517      * The zero in the reallen element means we won't pass a SIZE
1518      * option to ESMTP; the message length would be more trouble than
1519      * it's worth to compute.
1520      */
1521     struct msgblk reply = {NULL, NULL, "FETCHMAIL-DAEMON@", 0, 0};
1522     int status;
1523
1524     strlcat(reply.return_path, ctl->smtpaddress ? ctl->smtpaddress :
1525             fetchmailhost, sizeof(reply.return_path));
1526
1527     if (!MULTIDROP(ctl))                /* send to calling user */
1528     {
1529         save_str(&reply.recipients, ctl->localnames->id, XMIT_ACCEPT);
1530         status = open_sink(ctl, &reply, &good, &bad);
1531         free_str_list(&reply.recipients);
1532     }
1533     else                                /* send to postmaster  */
1534         status = open_sink(ctl, &reply, &good, &bad);
1535     if (status == 0) {
1536         stuff_warning(NULL, ctl, "From: FETCHMAIL-DAEMON@%s",
1537                 ctl->smtpaddress ? ctl->smtpaddress : fetchmailhost);
1538         stuff_warning(NULL, ctl, "Date: %s", rfc822timestamp());
1539         stuff_warning(NULL, ctl, "MIME-Version: 1.0");
1540         stuff_warning(NULL, ctl, "Content-Transfer-Encoding: 8bit");
1541         stuff_warning(NULL, ctl, "Content-Type: text/plain; charset=\"%s\"", iana_charset);
1542     }
1543     return(status);
1544 }
1545
1546 /* format and ship a warning message line by mail */
1547 /* if rfc2047charset is non-NULL, encode the line (that is assumed to be
1548  * a header line) as per RFC-2047 using rfc2047charset as the character
1549  * set field */
1550 #if defined(HAVE_STDARG_H)
1551 void stuff_warning(const char *rfc2047charset, struct query *ctl, const char *fmt, ... )
1552 #else
1553 void stuff_warning(rfc2047charset, ctl, fmt, va_alist)
1554 const char *charset;
1555 struct query *ctl;
1556 const char *fmt;        /* printf-style format */
1557 va_dcl
1558 #endif
1559 {
1560     /* make huge -- i18n can bulk up error messages a lot */
1561     char        buf[2*MSGBUFSIZE+4];
1562     va_list ap;
1563
1564     /*
1565      * stuffline() requires its input to be writeable (for CR stripping),
1566      * so we needed to copy the message to a writeable buffer anyway in
1567      * case it was a string constant.  We make a virtue of that necessity
1568      * here by supporting stdargs/varargs.
1569      */
1570 #if defined(HAVE_STDARG_H)
1571     va_start(ap, fmt) ;
1572 #else
1573     va_start(ap);
1574 #endif
1575     vsnprintf(buf, sizeof(buf) - 2, fmt, ap);
1576     va_end(ap);
1577
1578     snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1579
1580     /* guard against very long lines */
1581     buf[MSGBUFSIZE+1] = '\r';
1582     buf[MSGBUFSIZE+2] = '\n';
1583     buf[MSGBUFSIZE+3] = '\0';
1584
1585     stuffline(ctl, rfc2047charset != NULL ? rfc2047e(buf, rfc2047charset) : buf);
1586 }
1587
1588 void close_warning_by_mail(struct query *ctl, struct msgblk *msg)
1589 /* sign and send mailed warnings */
1590 {
1591     stuff_warning(NULL, ctl, GT_("-- \nThe Fetchmail Daemon"));
1592     close_sink(ctl, msg, TRUE);
1593 }
1594
1595 /* sink.c ends here */