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