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