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