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