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