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