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