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