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