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