]> Pileus Git - ~andy/fetchmail/blob - sink.c
Weird bug.
[~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
33 #include  "fetchmail.h"
34 #include  "socket.h"
35 #include  "smtp.h"
36
37 /* BSD portability hack...I know, this is an ugly place to put it */
38 #if !defined(SIGCHLD) && defined(SIGCLD)
39 #define SIGCHLD SIGCLD
40 #endif
41
42 #if INET6
43 #define SMTP_PORT       "smtp"  /* standard SMTP service port */
44 #else /* INET6 */
45 #define SMTP_PORT       25      /* standard SMTP service port */
46 #endif /* INET6 */
47
48 static int lmtp_responses;      /* how many should we expect? */
49 static struct msgblk msgcopy;   /* copies of various message internals */
50
51 static int smtp_open(struct query *ctl)
52 /* try to open a socket to the appropriate SMTP server for this query */ 
53 {
54     /* maybe it's time to close the socket in order to force delivery */
55     if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
56     {
57         close(ctl->smtp_socket);
58         ctl->smtp_socket = -1;
59         batchcount = 0;
60     }
61
62     /* if no socket to any SMTP host is already set up, try to open one */
63     if (ctl->smtp_socket == -1) 
64     {
65         /* 
66          * RFC 1123 requires that the domain name in HELO address is a
67          * "valid principal domain name" for the client host. If we're
68          * running in invisible mode, violate this with malice
69          * aforethought in order to make the Received headers and
70          * logging look right.
71          *
72          * In fact this code relies on the RFC1123 requirement that the
73          * SMTP listener must accept messages even if verification of the
74          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
75          *
76          * How we compute the true mailhost name to pass to the
77          * listener doesn't affect behavior on RFC1123- violating
78          * listeners that check for name match; we're going to lose
79          * on those anyway because we can never give them a name
80          * that matches the local machine fetchmail is running on.
81          * What it will affect is the listener's logging.
82          */
83         struct idlist   *idp;
84         const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
85         int oldphase = phase;
86
87         errno = 0;
88
89         /*
90          * Run down the SMTP hunt list looking for a server that's up.
91          * Use both explicit hunt entries (value TRUE) and implicit 
92          * (default) ones (value FALSE).
93          */
94         oldphase = phase;
95         phase = LISTENER_WAIT;
96
97         set_timeout(ctl->server.timeout);
98         for (idp = ctl->smtphunt; idp; idp = idp->next)
99         {
100             char        *cp, *parsed_host;
101 #ifdef INET6 
102             char        *portnum = SMTP_PORT;
103 #else
104             int         portnum = SMTP_PORT;
105 #endif /* INET6 */
106
107             xalloca(parsed_host, char *, strlen(idp->id) + 1);
108
109             ctl->smtphost = idp->id;  /* remember last host tried. */
110
111             strcpy(parsed_host, idp->id);
112             if ((cp = strrchr(parsed_host, '/')))
113             {
114                 *cp++ = 0;
115 #ifdef INET6 
116                 portnum = cp;
117 #else
118                 portnum = atoi(cp);
119 #endif /* INET6 */
120             }
121
122             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
123                                              ctl->server.plugout)) == -1)
124                 continue;
125
126             /* are we doing SMTP or LMTP? */
127             SMTP_setmode(ctl->listener);
128
129             /* first, probe for ESMTP */
130             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
131                     SMTP_ehlo(ctl->smtp_socket, id_me,
132                           &ctl->server.esmtp_options) == SM_OK)
133                break;  /* success */
134
135             /*
136              * RFC 1869 warns that some listeners hang up on a failed EHLO,
137              * so it's safest not to assume the socket will still be good.
138              */
139             SockClose(ctl->smtp_socket);
140             ctl->smtp_socket = -1;
141
142             /* if opening for ESMTP failed, try SMTP */
143             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
144                                              ctl->server.plugout)) == -1)
145                 continue;
146
147             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
148                     SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
149                 break;  /* success */
150
151             SockClose(ctl->smtp_socket);
152             ctl->smtp_socket = -1;
153         }
154         set_timeout(0);
155         phase = oldphase;
156     }
157
158     /*
159      * RFC 1123 requires that the domain name part of the
160      * RCPT TO address be "canonicalized", that is a FQDN
161      * or MX but not a CNAME.  Some listeners (like exim)
162      * enforce this.  Now that we have the actual hostname,
163      * compute what we should canonicalize with.
164      */
165     ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
166
167     if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
168         error(0, 0, "forwarding to %s", ctl->smtphost);
169
170     return(ctl->smtp_socket);
171 }
172
173 /* these are shared by open_sink and stuffline */
174 static FILE *sinkfp;
175 static RETSIGTYPE (*sigchld)(int);
176
177 int stuffline(struct query *ctl, char *buf)
178 /* ship a line to the given control block's output sink (SMTP server or MDA) */
179 {
180     int n, oldphase;
181     char *last;
182
183     /* The line may contain NUL characters. Find the last char to use
184      * -- the real line termination is the sequence "\n\0".
185      */
186     last = buf;
187     while ((last += strlen(last)) && (last[-1] != '\n'))
188         last++;
189
190     /* fix message lines that have only \n termination (for qmail) */
191     if (ctl->forcecr)
192     {
193         if (last - 1 == buf || last[-2] != '\r')
194         {
195             last[-1] = '\r';
196             *last++  = '\n';
197             *last    = '\0';
198         }
199     }
200
201     oldphase = phase;
202     phase = FORWARDING_WAIT;
203
204     /*
205      * SMTP byte-stuffing.  We only do this if the protocol does *not*
206      * use .<CR><LF> as EOM.  If it does, the server will already have
207      * decorated any . lines it sends back up.
208      */
209     if (*buf == '.')
210         if (ctl->server.base_protocol->delimited)       /* server has already byte-stuffed */
211         {
212             if (ctl->mda)
213                 ++buf;
214             else
215                 /* writing to SMTP, leave the byte-stuffing in place */;
216         }
217         else /* if (!protocol->delimited)       -- not byte-stuffed already */
218         {
219             if (!ctl->mda)
220                 SockWrite(ctl->smtp_socket, buf, 1);    /* byte-stuff it */
221             else
222                 /* leave it alone */;
223         }
224
225     /* we may need to strip carriage returns */
226     if (ctl->stripcr)
227     {
228         char    *sp, *tp;
229
230         for (sp = tp = buf; sp < last; sp++)
231             if (*sp != '\r')
232                 *tp++ =  *sp;
233         *tp = '\0';
234         last = tp;
235     }
236
237     n = 0;
238     if (ctl->mda || ctl->bsmtp)
239         n = fwrite(buf, 1, last - buf, sinkfp);
240     else if (ctl->smtp_socket != -1)
241         n = SockWrite(ctl->smtp_socket, buf, last - buf);
242
243     phase = oldphase;
244
245     return(n);
246 }
247
248 static void sanitize(char *s)
249 /* replace unsafe shellchars by an _ */
250 {
251     const static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
252     char *cp;
253
254     for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
255         *cp = '_';
256 }
257
258 int open_sink(struct query *ctl, struct msgblk *msg,
259               int *good_addresses, int *bad_addresses)
260 /* set up sinkfp to be an input sink we can ship a message to */
261 {
262     struct      idlist *idp;
263
264     *bad_addresses = *good_addresses = 0;
265
266     if (ctl->bsmtp)             /* dump to a BSMTP batch file */
267     {
268         if (strcmp(ctl->bsmtp, "-") == 0)
269             sinkfp = stdout;
270         else
271             sinkfp = fopen(ctl->bsmtp, "a");
272
273         /* see the ap computation under the SMTP branch */
274         fprintf(sinkfp, 
275                 "MAIL FROM: %s", (msg->return_path[0]) ? msg->return_path : user);
276
277         if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
278             fputs(" BODY=8BITMIME", sinkfp);
279         else if (ctl->mimemsg & MSG_IS_7BIT)
280             fputs(" BODY=7BIT", sinkfp);
281
282         fprintf(sinkfp, " SIZE=%ld\r\n", msg->reallen);
283
284         /*
285          * RFC 1123 requires that the domain name part of the
286          * RCPT TO address be "canonicalized", that is a FQDN
287          * or MX but not a CNAME.  Some listeners (like exim)
288          * enforce this.  Now that we have the actual hostname,
289          * compute what we should canonicalize with.
290          */
291         ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
292
293         *bad_addresses = 0;
294         for (idp = msg->xmit_names; idp; idp = idp->next)
295             if (idp->val.status.mark == XMIT_ACCEPT)
296             {
297                 if (strchr(idp->id, '@'))
298                     fprintf(sinkfp,
299                                 "RCPT TO: %s\r\n", idp->id);
300                 else
301                     fprintf(sinkfp,
302                                 "RCPT TO: %s@%s\r\n", idp->id, ctl->destaddr);
303                 *good_addresses = 0;
304             }
305
306         fputs("DATA\r\n", sinkfp);
307
308         if (ferror(sinkfp))
309         {
310             error(0, -1, "BSMTP file open or preamble write failed");
311             return(PS_BSMTP);
312         }
313     }
314     else if (ctl->mda)          /* we have a declared MDA */
315     {
316         int     length = 0, fromlen = 0, nameslen = 0;
317         char    *names = NULL, *before, *after, *from = NULL;
318
319         ctl->destaddr = "localhost";
320
321         for (idp = msg->xmit_names; idp; idp = idp->next)
322             if (idp->val.status.mark == XMIT_ACCEPT)
323                 (*good_addresses)++;
324
325         length = strlen(ctl->mda);
326         before = xstrdup(ctl->mda);
327
328         /* get user addresses for %T (or %s for backward compatibility) */
329         if (strstr(before, "%s") || strstr(before, "%T"))
330         {
331             /*
332              * We go through this in order to be able to handle very
333              * long lists of users and (re)implement %s.
334              */
335             nameslen = 0;
336             for (idp = msg->xmit_names; idp; idp = idp->next)
337                 if ((idp->val.status.mark == XMIT_ACCEPT))
338                     nameslen += (strlen(idp->id) + 1);  /* string + ' ' */
339             if ((*good_addresses == 0))
340                 nameslen = strlen(run.postmaster);
341
342             names = (char *)xmalloc(nameslen + 1);      /* account for '\0' */
343             if (*good_addresses == 0)
344                 strcpy(names, run.postmaster);
345             else
346             {
347                 names[0] = '\0';
348                 for (idp = msg->xmit_names; idp; idp = idp->next)
349                     if (idp->val.status.mark == XMIT_ACCEPT)
350                     {
351                         strcat(names, idp->id);
352                         strcat(names, " ");
353                     }
354                 names[--nameslen] = '\0';       /* chop trailing space */
355             }
356
357             /* sanitize names in order to contain only harmless shell chars */
358             sanitize(names);
359         }
360
361         /* get From address for %F */
362         if (strstr(before, "%F"))
363         {
364             from = xstrdup(msg->return_path);
365
366             /* sanitize from in order to contain *only* harmless shell chars */
367             sanitize(from);
368
369             fromlen = strlen(from);
370         }
371
372         /* do we have to build an mda string? */
373         if (names || from) 
374         {               
375             char        *sp, *dp;
376
377             /* find length of resulting mda string */
378             sp = before;
379             while ((sp = strstr(sp, "%s"))) {
380                 length += nameslen - 2; /* subtract %s */
381                 sp += 2;
382             }
383             sp = before;
384             while ((sp = strstr(sp, "%T"))) {
385                 length += nameslen - 2; /* subtract %T */
386                 sp += 2;
387             }
388             sp = before;
389             while ((sp = strstr(sp, "%F"))) {
390                 length += fromlen - 2;  /* subtract %F */
391                 sp += 2;
392             }
393                 
394             after = xmalloc(length + 1);
395
396             /* copy mda source string to after, while expanding %[sTF] */
397             for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
398                 if (sp[0] != '%')       continue;
399
400                 /* need to expand? BTW, no here overflow, because in
401                 ** the worst case (end of string) sp[1] == '\0' */
402                 if (sp[1] == 's' || sp[1] == 'T') {
403                     strcpy(dp, names);
404                     dp += nameslen;
405                     sp++;       /* position sp over [sT] */
406                     dp--;       /* adjust dp */
407                 } else if (sp[1] == 'F') {
408                     strcpy(dp, from);
409                     dp += fromlen;
410                     sp++;       /* position sp over F */
411                     dp--;       /* adjust dp */
412                 }
413             }
414
415             if (names) {
416                 free(names);
417                 names = NULL;
418             }
419             if (from) {
420                 free(from);
421                 from = NULL;
422             }
423
424             free(before);
425
426             before = after;
427         }
428
429
430         if (outlevel >= O_DEBUG)
431             error(0, 0, "about to deliver with: %s", before);
432
433 #ifdef HAVE_SETEUID
434         /*
435          * Arrange to run with user's permissions if we're root.
436          * This will initialize the ownership of any files the
437          * MDA creates properly.  (The seteuid call is available
438          * under all BSDs and Linux)
439          */
440         seteuid(ctl->uid);
441 #endif /* HAVE_SETEUID */
442
443         sinkfp = popen(before, "w");
444         free(before);
445         before = NULL;
446
447 #ifdef HAVE_SETEUID
448         /* this will fail quietly if we didn't start as root */
449         seteuid(0);
450 #endif /* HAVE_SETEUID */
451
452         if (!sinkfp)
453         {
454             error(0, 0, "MDA open failed");
455             return(PS_IOERR);
456         }
457
458         sigchld = signal(SIGCHLD, SIG_DFL);
459     }
460     else /* forward to an SMTP listener */
461     {
462         const char      *ap;
463         char    options[MSGBUFSIZE], addr[128];
464
465         /* build a connection to the SMTP listener */
466         if ((smtp_open(ctl) == -1))
467         {
468             error(0, errno, "%cMTP connect to %s failed",
469                   ctl->listener,
470                   ctl->smtphost ? ctl->smtphost : "localhost");
471             return(PS_SMTP);
472         }
473
474         /*
475          * Stash a copy of the parsed message block 
476          * for use by close_sink().
477          */
478         memcpy(&msgcopy, msg, sizeof(struct msgblk));
479
480         /*
481          * Compute ESMTP options.
482          */
483         options[0] = '\0';
484         if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
485              if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
486                 strcpy(options, " BODY=8BITMIME");
487              else if (ctl->mimemsg & MSG_IS_7BIT)
488                 strcpy(options, " BODY=7BIT");
489         }
490
491         if ((ctl->server.esmtp_options & ESMTP_SIZE) && msg->reallen > 0)
492             sprintf(options + strlen(options), " SIZE=%ld", msg->reallen);
493
494         /*
495          * Try to get the SMTP listener to take the Return-Path
496          * address as MAIL FROM .  If it won't, fall back on the
497          * calling-user ID.  This won't affect replies, which use the
498          * header From address anyway.
499          *
500          * RFC 1123 requires that the domain name part of the
501          * MAIL FROM address be "canonicalized", that is a
502          * FQDN or MX but not a CNAME.  We'll assume the From
503          * header is already in this form here (it certainly
504          * is if rewrite is on).  RFC 1123 is silent on whether
505          * a nonexistent hostname part is considered canonical.
506          *
507          * This is a potential problem if the MTAs further upstream
508          * didn't pass canonicalized From/Return-Path lines, *and* the
509          * local SMTP listener insists on them.
510          *
511          * None of these error conditions generates bouncemail.  Comments
512          * below explain for each case why this is so.
513          */
514         ap = (msg->return_path[0]) ? msg->return_path : user;
515         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
516         {
517             int smtperr = atoi(smtp_response);
518
519             if (str_find(&ctl->antispam, smtperr))
520             {
521                 /*
522                  * SMTP listener explicitly refuses to deliver mail
523                  * coming from this address, probably due to an
524                  * anti-spam domain exclusion.  Respect this.  Don't
525                  * try to ship the message, and don't prevent it from
526                  * being deleted.  Typical values:
527                  *
528                  * 501 = exim's old antispam response
529                  * 550 = exim's new antispam response (temporary)
530                  * 553 = sendmail 8.8.7's generic REJECT 
531                  * 571 = sendmail's "unsolicited email refused"
532                  *
533                  * We don't send bouncemail on antispam failures because
534                  * we don't want the scumbags to know the address is even
535                  * valid.
536                  */
537                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
538                 return(PS_REFUSED);
539             }
540
541             /*
542              * Suppress error message only if the response specifically 
543              * meant `excluded for policy reasons'.  We *should* see
544              * an error when the return code is less specific.
545              */
546             if (smtperr >= 400)
547                 error(0, -1, "%cMTP error: %s", 
548                       ctl->listener,
549                       smtp_response);
550
551             switch (smtperr)
552             {
553             case 452: /* insufficient system storage */
554                 /*
555                  * Temporary out-of-queue-space condition on the
556                  * ESMTP server.  Don't try to ship the message, 
557                  * and suppress deletion so it can be retried on
558                  * a future retrieval cycle. 
559                  *
560                  * Bouncemail *might* be appropriate here as a delay
561                  * notification.  But it's not really necessary because
562                  * this is not an actual failure, we're very likely to be
563                  * able to recover on the next cycle.
564                  */
565                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
566                 return(PS_TRANSIENT);
567
568             case 552: /* message exceeds fixed maximum message size */
569             case 553: /* invalid sending domain */
570                 /*
571                  * Permanent no-go condition on the
572                  * ESMTP server.  Don't try to ship the message, 
573                  * and allow it to be deleted.
574                  *
575                  * Bouncemail would be appropriate for 552, but in these 
576                  * latter days 553 usually means a spammer is trying to
577                  * cover his tracks.  We'd rather deny the scumbags any
578                  * feedback that the address is valid.
579                  */
580                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
581                 return(PS_REFUSED);
582
583             default:    /* retry with postmaster's address */
584                 if (SMTP_from(ctl->smtp_socket,run.postmaster,options)!=SM_OK)
585                 {
586                     error(0, -1, "%cMTP error: %s",
587                           ctl->listener,
588                           smtp_response);
589                     return(PS_SMTP);    /* should never happen */
590                 }
591             }
592         }
593
594         /*
595          * Now list the recipient addressees
596          */
597         for (idp = msg->xmit_names; idp; idp = idp->next)
598             if (idp->val.status.mark == XMIT_ACCEPT)
599             {
600                 if (strchr(idp->id, '@'))
601                     strcpy(addr, idp->id);
602                 else
603 #ifdef HAVE_SNPRINTF
604                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, ctl->destaddr);
605 #else
606                     sprintf(addr, "%s@%s", idp->id, ctl->destaddr);
607 #endif /* HAVE_SNPRINTF */
608
609                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
610                     (*good_addresses)++;
611                 else
612                 {
613                     (*bad_addresses)++;
614                     idp->val.status.mark = XMIT_ANTISPAM;
615                     error(0, 0, 
616                           "%cMTP listener doesn't like recipient address `%s'",
617                           ctl->listener, addr);
618                 }
619             }
620         if (!(*good_addresses))
621         {
622 #ifdef HAVE_SNPRINTF
623             snprintf(addr, sizeof(addr)-1, "%s@%s", run.postmaster, ctl->destaddr);
624 #else
625             sprintf(addr, "%s@%s", run.postmaster, ctl->destaddr);
626 #endif /* HAVE_SNPRINTF */
627
628             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
629             {
630                 error(0, 0, "can't even send to %s!", run.postmaster);
631                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
632                 return(PS_SMTP);
633             }
634         }
635
636         /* tell it we're ready to send data */
637         SMTP_data(ctl->smtp_socket);
638     }
639
640     /*
641      * We need to stash this away in order to know how many
642      * response lines to expect after the LMTP end-of-message.
643      */
644     lmtp_responses = *good_addresses;
645
646     return(PS_SUCCESS);
647 }
648
649 void release_sink(struct query *ctl)
650 /* release the per-message output sink, whether it's a pipe or SMTP socket */
651 {
652     if (ctl->bsmtp)
653         fclose(sinkfp);
654     else if (ctl->mda)
655     {
656         if (sinkfp)
657         {
658             pclose(sinkfp);
659             sinkfp = (FILE *)NULL;
660         }
661         signal(SIGCHLD, sigchld);
662     }
663 }
664
665 int close_sink(struct query *ctl, flag forward)
666 /* perform end-of-message actions on the current output sink */
667 {
668     if (ctl->mda)
669     {
670         int rc;
671
672         /* close the delivery pipe, we'll reopen before next message */
673         if (sinkfp)
674         {
675             rc = pclose(sinkfp);
676             sinkfp = (FILE *)NULL;
677         }
678         else
679             rc = 0;
680         signal(SIGCHLD, sigchld);
681         if (rc)
682         {
683             error(0, -1, "MDA exited abnormally or returned nonzero status");
684             return(FALSE);
685         }
686     }
687     else if (ctl->bsmtp)
688     {
689         /* implicit disk-full check here... */
690         fputs("..\r\n", sinkfp);
691         if (strcmp(ctl->bsmtp, "-"))
692             fclose(sinkfp);
693         if (ferror(sinkfp))
694         {
695             error(0, -1, "Message termination or close of BSMTP file failed");
696             return(FALSE);
697         }
698     }
699     else if (forward)
700     {
701         /* write message terminator */
702         if (SMTP_eom(ctl->smtp_socket) != SM_OK)
703         {
704             error(0, -1, "SMTP listener refused delivery");
705             return(FALSE);
706         }
707
708         /*
709          * If this is an SMTP connection, SMTP_eom() ate the response.
710          * But could be this is an LMTP connection, in which case we have to
711          * interpret either (a) a single 503 response meaning there
712          * were no successful RCPT TOs, or (b) a variable number of
713          * responses, one for each successful RCPT TO.  We need to send
714          * bouncemail on each failed response and then return TRUE anyway,
715          * otherwise the message will get left in the queue and resent
716          * to people who got it the first time.
717          */
718         if (ctl->listener == LMTP_MODE)
719             if (lmtp_responses == 0)
720             {
721                 SMTP_ok(ctl->smtp_socket); 
722
723                 /*
724                  * According to RFC2033, 503 is the only legal response
725                  * if no RCPT TO commands succeeded.  No error recovery
726                  * is really possible here, as we have no idea what
727                  * insane thing the listener might be doing if it doesn't
728                  * comply.
729                  */
730                 if (atoi(smtp_response) == 503)
731                     error(0, -1, "LMTP delivery error on EOM");
732                 else
733                     error(0, -1,
734                           "Unexpected non-503 response to LMTP EOM: %s",
735                           smtp_response);
736
737                 /*
738                  * It's not completely clear what to do here.  We choose to
739                  * interpret delivery failure here as a transient error, 
740                  * the same way SMTP delivery failure is handled.  If we're
741                  * wrong, an undead message will get stuck in the queue.
742                  */
743                 return(FALSE);
744             }
745             else
746             {
747                 int     i, errors;
748                 char    **responses;
749
750                 /* eat the RFC2033-required responses, saving errors */ 
751                 xalloca(responses, char **, sizeof(char *) * lmtp_responses);
752                 for (errors = i = 0; i < lmtp_responses; i++)
753                 {
754                     if (SMTP_ok(ctl->smtp_socket) == SM_OK)
755                         responses[i] = (char *)NULL;
756                     else
757                     {
758                         xalloca(responses[errors], 
759                                 char *, 
760                                 strlen(smtp_response)+1);
761                         strcpy(responses[errors], smtp_response);
762                         errors++;
763                     }
764                 }
765
766                 if (errors == 0)
767                     return(TRUE);       /* all deliveries succeeded */
768                 else if (errors == lmtp_responses)
769                     return(FALSE);      /* all deliveries failed */
770                 else
771                 {
772                     /*
773                      * Now life gets messy.  There are multiple recipients,
774                      * and one or more (but not all) deliveries failed.
775                      *
776                      * What we'd really like to do is bounce a
777                      * failures list back to the sender and return
778                      * TRUE, deleting the message from the server so
779                      * it won't be re-forwarded on subsequent poll
780                      * cycles.
781                      *
782                      * We can't do that yet, so instead we report 
783                      * failures to the calling-user/postmaster.  If we can't,
784                      * there's a transient error in local delivery; leave
785                      * the message on the server.
786                      */
787                     char buf[MSGBUFSIZE];
788
789                     if (open_warning_by_mail(ctl))
790                         return(FALSE);
791
792                     /* generate an error report a la RFC 1892 */
793                     stuff_warning(ctl, "MIME-Version: 1.0");
794                     stuff_warning(ctl, "Content-Type: multipart/report report-type=text/plain boundary=\"om-mani-padme-hum\"");
795                     stuff_warning(ctl, "Content-Transfer-Encoding: 7bit");
796                     stuff_warning(ctl, "");
797
798
799                     /* RFC1892 part 1 -- human-readable message */
800                     stuff_warning(ctl, "-- om-mani-padme-hum"); 
801                     stuff_warning(ctl, "");
802
803                     /* RFC1892 part 2 -- machine-readable responses */
804                     stuff_warning(ctl, "-- om-mani-padme-hum"); 
805                     stuff_warning(ctl,"Content-Type: message/delivery-status");
806                     stuff_warning(ctl, "");
807                     for (i = 0; i < errors; i++)
808                         stuff_warning(ctl, responses[i]);
809
810                     /* RFC1892 part 3 -- headers of undelivered message */
811                     stuff_warning(ctl, "-- om-mani-padme-hum"); 
812                     stuff_warning(ctl, "Content-Type: text/rfc822-headers");
813                     stuff_warning(ctl, "");
814                     stuffline(ctl, msgcopy.headers);
815
816                     stuff_warning(ctl, "-- om-mani-padme-hum --"); 
817
818                     close_warning_by_mail(ctl);
819
820                     /*
821                      * It's not completely clear what to do here,
822                      * either.  We choose to interpret delivery
823                      * failure here as a permanent error, so the
824                      * people who got successful deliveries won't see
825                      * endless repetitions of the same message on
826                      * subsequent poll messages.  If we're wrong, a
827                      * transient error will cause someone to lose
828                      * mail.  This could only happen with
829                      * multi-recipient messages coming from a remote
830                      * mailserver to two or more local users...
831                      */
832                     return(TRUE);
833                 }
834             }
835     }
836
837     return(TRUE);
838 }
839
840 int open_warning_by_mail(struct query *ctl)
841 /* set up output sink for a mailed warning to calling user */
842 {
843     int good, bad;
844     static struct msgblk msg = {NULL, NULL, "FETCHMAIL-DAEMON", 0};
845
846     /*
847      * We give a null address list as arg 4 because we actually *want*
848      * this message to go to run.postmaster.  The zero length arg 5 means
849      * we won't pass a SIZE option to ESMTP; the message length would
850      * be more trouble than it's worth to compute.
851      */
852     return(open_sink(ctl, &msg, &good, &bad));
853 }
854
855 #if defined(HAVE_STDARG_H)
856 void stuff_warning(struct query *ctl, const char *fmt, ... )
857 #else
858 void stuff_warning(struct query *ctl, fmt, va_alist)
859 struct query *ctl;
860 const char *fmt;        /* printf-style format */
861 va_dcl
862 #endif
863 /* format and ship a warning message line by mail */
864 {
865     char        buf[POPBUFSIZE];
866     va_list ap;
867
868     /*
869      * stuffline() requires its input to be writeable (for CR stripping),
870      * so we needed to copy the message to a writeable buffer anyway in
871      * case it was a string constant.  We make a virtue of that necessity
872      * here by supporting stdargs/varargs.
873      */
874 #if defined(HAVE_STDARG_H)
875     va_start(ap, fmt) ;
876 #else
877     va_start(ap);
878 #endif
879 #ifdef HAVE_VSNPRINTF
880     vsnprintf(buf, sizeof(buf), fmt, ap);
881 #else
882     vsprintf(buf, fmt, ap);
883 #endif
884     va_end(ap);
885
886     strcat(buf, "\r\n");
887
888     stuffline(ctl, buf);
889 }
890
891 void close_warning_by_mail(struct query *ctl)
892 /* sign and send mailed warnings */
893 {
894     stuff_warning(ctl, "--\r\n\t\t\t\tThe Fetchmail Daemon\r\n");
895     close_sink(ctl, TRUE);
896 }
897
898 /* sink.c ends here */