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