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