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