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