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