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