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