]> Pileus Git - ~andy/fetchmail/blob - sink.c
Added plugin/plugout option.
[~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 SMTP
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
28 #include  "fetchmail.h"
29 #include  "socket.h"
30 #include  "smtp.h"
31
32 /* BSD portability hack...I know, this is an ugly place to put it */
33 #if !defined(SIGCHLD) && defined(SIGCLD)
34 #define SIGCHLD SIGCLD
35 #endif
36
37 #if INET6
38 #define SMTP_PORT       "smtp"  /* standard SMTP service port */
39 #else /* INET6 */
40 #define SMTP_PORT       25      /* standard SMTP service port */
41 #endif /* INET6 */
42
43 static int smtp_open(struct query *ctl)
44 /* try to open a socket to the appropriate SMTP server for this query */ 
45 {
46     /* maybe it's time to close the socket in order to force delivery */
47     if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
48     {
49         close(ctl->smtp_socket);
50         ctl->smtp_socket = -1;
51         batchcount = 0;
52     }
53
54     /* if no socket to any SMTP host is already set up, try to open one */
55     if (ctl->smtp_socket == -1) 
56     {
57         /* 
58          * RFC 1123 requires that the domain name in HELO address is a
59          * "valid principal domain name" for the client host. If we're
60          * running in invisible mode, violate this with malice
61          * aforethought in order to make the Received headers and
62          * logging look right.
63          *
64          * In fact this code relies on the RFC1123 requirement that the
65          * SMTP listener must accept messages even if verification of the
66          * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
67          *
68          * How we compute the true mailhost name to pass to the
69          * listener doesn't affect behavior on RFC1123- violating
70          * listeners that check for name match; we're going to lose
71          * on those anyway because we can never give them a name
72          * that matches the local machine fetchmail is running on.
73          * What it will affect is the listener's logging.
74          */
75         struct idlist   *idp;
76         const char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
77         int oldphase = phase;
78
79         errno = 0;
80
81         /*
82          * Run down the SMTP hunt list looking for a server that's up.
83          * Use both explicit hunt entries (value TRUE) and implicit 
84          * (default) ones (value FALSE).
85          */
86         oldphase = phase;
87         phase = LISTENER_WAIT;
88
89         set_timeout(ctl->server.timeout);
90         for (idp = ctl->smtphunt; idp; idp = idp->next)
91         {
92             char        *cp, *parsed_host;
93 #ifdef INET6 
94             char        *portnum = SMTP_PORT;
95 #else
96             int         portnum = SMTP_PORT;
97 #endif /* INET6 */
98
99             xalloca(parsed_host, char *, strlen(idp->id) + 1);
100
101             ctl->smtphost = idp->id;  /* remember last host tried. */
102
103             strcpy(parsed_host, idp->id);
104             if ((cp = strrchr(parsed_host, '/')))
105             {
106                 *cp++ = 0;
107 #ifdef INET6 
108                 portnum = cp;
109 #else
110                 portnum = atoi(cp);
111 #endif /* INET6 */
112             }
113
114             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
115                                              ctl->server.plugout)) == -1)
116                 continue;
117
118             /* first, probe for ESMTP */
119             if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
120                     SMTP_ehlo(ctl->smtp_socket, id_me,
121                           &ctl->server.esmtp_options) == SM_OK)
122                break;  /* success */
123
124             /*
125              * RFC 1869 warns that some listeners hang up on a failed EHLO,
126              * so it's safest not to assume the socket will still be good.
127              */
128             SockClose(ctl->smtp_socket);
129             ctl->smtp_socket = -1;
130
131             /* if opening for ESMTP failed, try SMTP */
132             if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL,
133                                              ctl->server.plugout)) == -1)
134                 continue;
135
136             if (SMTP_ok(ctl->smtp_socket) == SM_OK && 
137                     SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
138                 break;  /* success */
139
140             SockClose(ctl->smtp_socket);
141             ctl->smtp_socket = -1;
142         }
143         set_timeout(0);
144         phase = oldphase;
145     }
146
147     /*
148      * RFC 1123 requires that the domain name part of the
149      * RCPT TO address be "canonicalized", that is a FQDN
150      * or MX but not a CNAME.  Some listeners (like exim)
151      * enforce this.  Now that we have the actual hostname,
152      * compute what we should canonicalize with.
153      */
154     ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
155
156     if (outlevel >= O_DEBUG && ctl->smtp_socket != -1)
157         error(0, 0, "forwarding to %s", ctl->smtphost);
158
159     return(ctl->smtp_socket);
160 }
161
162 /* these are shared by open_sink and stuffline */
163 static FILE *sinkfp;
164 static RETSIGTYPE (*sigchld)(int);
165
166 int stuffline(struct query *ctl, char *buf)
167 /* ship a line to the given control block's output sink (SMTP server or MDA) */
168 {
169     int n, oldphase;
170     char *last;
171
172     /* The line may contain NUL characters. Find the last char to use
173      * -- the real line termination is the sequence "\n\0".
174      */
175     last = buf;
176     while ((last += strlen(last)) && (last[-1] != '\n'))
177         last++;
178
179     /* fix message lines that have only \n termination (for qmail) */
180     if (ctl->forcecr)
181     {
182         if (last - 1 == buf || last[-2] != '\r')
183         {
184             last[-1] = '\r';
185             *last++  = '\n';
186             *last    = '\0';
187         }
188     }
189
190     oldphase = phase;
191     phase = FORWARDING_WAIT;
192
193     /*
194      * SMTP byte-stuffing.  We only do this if the protocol does *not*
195      * use .<CR><LF> as EOM.  If it does, the server will already have
196      * decorated any . lines it sends back up.
197      */
198     if (*buf == '.')
199         if (ctl->server.base_protocol->delimited)       /* server has already byte-stuffed */
200         {
201             if (ctl->mda)
202                 ++buf;
203             else
204                 /* writing to SMTP, leave the byte-stuffing in place */;
205         }
206         else /* if (!protocol->delimited)       -- not byte-stuffed already */
207         {
208             if (!ctl->mda)
209                 SockWrite(ctl->smtp_socket, buf, 1);    /* byte-stuff it */
210             else
211                 /* leave it alone */;
212         }
213
214     /* we may need to strip carriage returns */
215     if (ctl->stripcr)
216     {
217         char    *sp, *tp;
218
219         for (sp = tp = buf; sp < last; sp++)
220             if (*sp != '\r')
221                 *tp++ =  *sp;
222         *tp = '\0';
223         last = tp;
224     }
225
226     n = 0;
227     if (ctl->mda || ctl->bsmtp)
228         n = fwrite(buf, 1, last - buf, sinkfp);
229     else if (ctl->smtp_socket != -1)
230         n = SockWrite(ctl->smtp_socket, buf, last - buf);
231
232     phase = oldphase;
233
234     return(n);
235 }
236
237 static void sanitize(char *s)
238 /* replace unsafe shellchars by an _ */
239 {
240     const static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
241     char *cp;
242
243     for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
244         *cp = '_';
245 }
246
247 int open_sink(struct query *ctl, 
248               const char *return_path,
249               struct idlist *xmit_names,
250               long reallen,
251               int *good_addresses, int *bad_addresses)
252 /* set up sinkfp to be an input sink we can ship a message to */
253 {
254     struct      idlist *idp;
255
256     *bad_addresses = *good_addresses = 0;
257
258     if (ctl->bsmtp)             /* dump to a BSMTP batch file */
259     {
260         if (strcmp(ctl->bsmtp, "-") == 0)
261             sinkfp = stdout;
262         else
263             sinkfp = fopen(ctl->bsmtp, "a");
264
265         /* see the ap computation under the SMTP branch */
266         fprintf(sinkfp, 
267                 "MAIL FROM: %s", (return_path[0]) ? return_path : user);
268
269         if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
270             fputs(" BODY=8BITMIME", sinkfp);
271         else if (ctl->mimemsg & MSG_IS_7BIT)
272             fputs(" BODY=7BIT", sinkfp);
273
274         fprintf(sinkfp, " SIZE=%ld\r\n", reallen);
275
276         /*
277          * RFC 1123 requires that the domain name part of the
278          * RCPT TO address be "canonicalized", that is a FQDN
279          * or MX but not a CNAME.  Some listeners (like exim)
280          * enforce this.  Now that we have the actual hostname,
281          * compute what we should canonicalize with.
282          */
283         ctl->destaddr = ctl->smtpaddress ? ctl->smtpaddress : "localhost";
284
285         *bad_addresses = 0;
286         for (idp = xmit_names; idp; idp = idp->next)
287             if (idp->val.status.mark == XMIT_ACCEPT)
288             {
289                 if (strchr(idp->id, '@'))
290                     fprintf(sinkfp,
291                                 "RCPT TO: %s\r\n", idp->id);
292                 else
293                     fprintf(sinkfp,
294                                 "RCPT TO: %s@%s\r\n", idp->id, ctl->destaddr);
295                 *good_addresses = 0;
296             }
297
298         fputs("DATA\r\n", sinkfp);
299
300         if (ferror(sinkfp))
301         {
302             error(0, -1, "BSMTP file open or preamble write failed");
303             return(PS_BSMTP);
304         }
305     }
306     else if (ctl->mda)          /* we have a declared MDA */
307     {
308         int     length = 0, fromlen = 0, nameslen = 0;
309         char    *names = NULL, *before, *after, *from = NULL;
310
311         ctl->destaddr = "localhost";
312
313         for (idp = xmit_names; idp; idp = idp->next)
314             if (idp->val.status.mark == XMIT_ACCEPT)
315                 (*good_addresses)++;
316
317         length = strlen(ctl->mda);
318         before = xstrdup(ctl->mda);
319
320         /* get user addresses for %T (or %s for backward compatibility) */
321         if (strstr(before, "%s") || strstr(before, "%T"))
322         {
323             /*
324              * We go through this in order to be able to handle very
325              * long lists of users and (re)implement %s.
326              */
327             nameslen = 0;
328             for (idp = xmit_names; idp; idp = idp->next)
329                 if ((idp->val.status.mark == XMIT_ACCEPT))
330                     nameslen += (strlen(idp->id) + 1);  /* string + ' ' */
331             if ((*good_addresses == 0))
332                 nameslen = strlen(run.postmaster);
333
334             names = (char *)xmalloc(nameslen + 1);      /* account for '\0' */
335             if (*good_addresses == 0)
336                 strcpy(names, run.postmaster);
337             else
338             {
339                 names[0] = '\0';
340                 for (idp = xmit_names; idp; idp = idp->next)
341                     if (idp->val.status.mark == XMIT_ACCEPT)
342                     {
343                         strcat(names, idp->id);
344                         strcat(names, " ");
345                     }
346                 names[--nameslen] = '\0';       /* chop trailing space */
347             }
348
349             /* sanitize names in order to contain only harmless shell chars */
350             sanitize(names);
351         }
352
353         /* get From address for %F */
354         if (strstr(before, "%F"))
355         {
356             from = xstrdup(return_path);
357
358             /* sanitize from in order to contain *only* harmless shell chars */
359             sanitize(from);
360
361             fromlen = strlen(from);
362         }
363
364         /* do we have to build an mda string? */
365         if (names || from) 
366         {               
367             char        *sp, *dp;
368
369             /* find length of resulting mda string */
370             sp = before;
371             while ((sp = strstr(sp, "%s"))) {
372                 length += nameslen - 2; /* subtract %s */
373                 sp += 2;
374             }
375             sp = before;
376             while ((sp = strstr(sp, "%T"))) {
377                 length += nameslen - 2; /* subtract %T */
378                 sp += 2;
379             }
380             sp = before;
381             while ((sp = strstr(sp, "%F"))) {
382                 length += fromlen - 2;  /* subtract %F */
383                 sp += 2;
384             }
385                 
386             after = xmalloc(length + 1);
387
388             /* copy mda source string to after, while expanding %[sTF] */
389             for (dp = after, sp = before; (*dp = *sp); dp++, sp++) {
390                 if (sp[0] != '%')       continue;
391
392                 /* need to expand? BTW, no here overflow, because in
393                 ** the worst case (end of string) sp[1] == '\0' */
394                 if (sp[1] == 's' || sp[1] == 'T') {
395                     strcpy(dp, names);
396                     dp += nameslen;
397                     sp++;       /* position sp over [sT] */
398                     dp--;       /* adjust dp */
399                 } else if (sp[1] == 'F') {
400                     strcpy(dp, from);
401                     dp += fromlen;
402                     sp++;       /* position sp over F */
403                     dp--;       /* adjust dp */
404                 }
405             }
406
407             if (names) {
408                 free(names);
409                 names = NULL;
410             }
411             if (from) {
412                 free(from);
413                 from = NULL;
414             }
415
416             free(before);
417
418             before = after;
419         }
420
421
422         if (outlevel >= O_DEBUG)
423             error(0, 0, "about to deliver with: %s", before);
424
425 #ifdef HAVE_SETEUID
426         /*
427          * Arrange to run with user's permissions if we're root.
428          * This will initialize the ownership of any files the
429          * MDA creates properly.  (The seteuid call is available
430          * under all BSDs and Linux)
431          */
432         seteuid(ctl->uid);
433 #endif /* HAVE_SETEUID */
434
435         sinkfp = popen(before, "w");
436         free(before);
437         before = NULL;
438
439 #ifdef HAVE_SETEUID
440         /* this will fail quietly if we didn't start as root */
441         seteuid(0);
442 #endif /* HAVE_SETEUID */
443
444         if (!sinkfp)
445         {
446             error(0, 0, "MDA open failed");
447             return(PS_IOERR);
448         }
449
450         sigchld = signal(SIGCHLD, SIG_DFL);
451     }
452     else /* forward to an SMTP listener */
453     {
454         const char      *ap;
455         char    options[MSGBUFSIZE], addr[128];
456
457         /* build a connection to the SMTP listener */
458         if ((smtp_open(ctl) == -1))
459         {
460             error(0, errno, "SMTP connect to %s failed",
461                   ctl->smtphost ? ctl->smtphost : "localhost");
462             return(PS_SMTP);
463         }
464
465         /*
466          * Compute ESMTP options.
467          */
468         options[0] = '\0';
469         if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
470              if (ctl->pass8bits || (ctl->mimemsg & MSG_IS_8BIT))
471                 strcpy(options, " BODY=8BITMIME");
472              else if (ctl->mimemsg & MSG_IS_7BIT)
473                 strcpy(options, " BODY=7BIT");
474         }
475
476         if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
477             sprintf(options + strlen(options), " SIZE=%ld", reallen);
478
479         /*
480          * Try to get the SMTP listener to take the Return-Path
481          * address as MAIL FROM .  If it won't, fall back on the
482          * calling-user ID.  This won't affect replies, which use the
483          * header From address anyway.
484          *
485          * RFC 1123 requires that the domain name part of the
486          * MAIL FROM address be "canonicalized", that is a
487          * FQDN or MX but not a CNAME.  We'll assume the From
488          * header is already in this form here (it certainly
489          * is if rewrite is on).  RFC 1123 is silent on whether
490          * a nonexistent hostname part is considered canonical.
491          *
492          * This is a potential problem if the MTAs further upstream
493          * didn't pass canonicalized From/Return-Path lines, *and* the
494          * local SMTP listener insists on them.
495          *
496          * None of these error conditions generates bouncemail.  Comments
497          * below explain for each case why this is so.
498          */
499         ap = (return_path[0]) ? return_path : user;
500         if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
501         {
502             int smtperr = atoi(smtp_response);
503
504             if (str_find(&ctl->antispam, smtperr))
505             {
506                 /*
507                  * SMTP listener explicitly refuses to deliver mail
508                  * coming from this address, probably due to an
509                  * anti-spam domain exclusion.  Respect this.  Don't
510                  * try to ship the message, and don't prevent it from
511                  * being deleted.  Typical values:
512                  *
513                  * 501 = exim's old antispam response
514                  * 550 = exim's new antispam response (temporary)
515                  * 553 = sendmail 8.8.7's generic REJECT 
516                  * 571 = sendmail's "unsolicited email refused"
517                  *
518                  * We don't send bouncemail on antispam failures because
519                  * we don't want the scumbags to know the address is even
520                  * valid.
521                  */
522                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
523                 return(PS_REFUSED);
524             }
525
526             /*
527              * Suppress error message only if the response specifically 
528              * meant `excluded for policy reasons'.  We *should* see
529              * an error when the return code is less specific.
530              */
531             if (smtperr >= 400)
532                 error(0, -1, "SMTP error: %s", smtp_response);
533
534             switch (smtperr)
535             {
536             case 452: /* insufficient system storage */
537                 /*
538                  * Temporary out-of-queue-space condition on the
539                  * ESMTP server.  Don't try to ship the message, 
540                  * and suppress deletion so it can be retried on
541                  * a future retrieval cycle. 
542                  *
543                  * Bouncemail *might* be appropriate here as a delay
544                  * notification.  But it's not really necessary because
545                  * this is not an actual failure, we're very likely to be
546                  * able to recover on the next cycle.
547                  */
548                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
549                 return(PS_TRANSIENT);
550
551             case 552: /* message exceeds fixed maximum message size */
552             case 553: /* invalid sending domain */
553                 /*
554                  * Permanent no-go condition on the
555                  * ESMTP server.  Don't try to ship the message, 
556                  * and allow it to be deleted.
557                  *
558                  * Bouncemail would be appropriate for 552, but in these 
559                  * latter days 553 usually means a spammer is trying to
560                  * cover his tracks.  We'd rather deny the scumbags any
561                  * feedback that the address is valid.
562                  */
563                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
564                 return(PS_REFUSED);
565
566             default:    /* retry with postmaster's address */
567                 if (SMTP_from(ctl->smtp_socket,run.postmaster,options)!=SM_OK)
568                 {
569                     error(0, -1, "SMTP error: %s", smtp_response);
570                     return(PS_SMTP);    /* should never happen */
571                 }
572             }
573         }
574
575         /*
576          * Now list the recipient addressees
577          */
578         for (idp = xmit_names; idp; idp = idp->next)
579             if (idp->val.status.mark == XMIT_ACCEPT)
580             {
581                 if (strchr(idp->id, '@'))
582                     strcpy(addr, idp->id);
583                 else
584 #ifdef HAVE_SNPRINTF
585                     snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, ctl->destaddr);
586 #else
587                     sprintf(addr, "%s@%s", idp->id, ctl->destaddr);
588 #endif /* HAVE_SNPRINTF */
589
590                 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
591                     (*good_addresses)++;
592                 else
593                 {
594                     (*bad_addresses)++;
595                     idp->val.status.mark = XMIT_ANTISPAM;
596                     error(0, 0, 
597                           "SMTP listener doesn't like recipient address `%s'",
598                           addr);
599                 }
600             }
601         if (!(*good_addresses))
602         {
603 #ifdef HAVE_SNPRINTF
604             snprintf(addr, sizeof(addr)-1, "%s@%s", run.postmaster, ctl->destaddr);
605 #else
606             sprintf(addr, "%s@%s", run.postmaster, ctl->destaddr);
607 #endif /* HAVE_SNPRINTF */
608
609             if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
610             {
611                 error(0, 0, "can't even send to %s!", run.postmaster);
612                 SMTP_rset(ctl->smtp_socket);    /* required by RFC1870 */
613                 return(PS_SMTP);
614             }
615         }
616
617         /* tell it we're ready to send data */
618         SMTP_data(ctl->smtp_socket);
619     }
620
621     return(PS_SUCCESS);
622 }
623
624 void release_sink(struct query *ctl)
625 /* release the per-message output sink, whether it's a pipe or SMTP socket */
626 {
627     if (ctl->bsmtp)
628         fclose(sinkfp);
629     else if (ctl->mda)
630     {
631         if (sinkfp)
632         {
633             pclose(sinkfp);
634             sinkfp = (FILE *)NULL;
635         }
636         signal(SIGCHLD, sigchld);
637     }
638 }
639
640 int close_sink(struct query *ctl, flag forward)
641 /* perform end-of-message actions on the current output sink */
642 {
643     if (ctl->mda)
644     {
645         int rc;
646
647         /* close the delivery pipe, we'll reopen before next message */
648         if (sinkfp)
649         {
650             rc = pclose(sinkfp);
651             sinkfp = (FILE *)NULL;
652         }
653         else
654             rc = 0;
655         signal(SIGCHLD, sigchld);
656         if (rc)
657         {
658             error(0, -1, "MDA exited abnormally or returned nonzero status");
659             return(FALSE);
660         }
661     }
662     else if (ctl->bsmtp)
663     {
664         /* implicit disk-full check here... */
665         fputs("..\r\n", sinkfp);
666         if (strcmp(ctl->bsmtp, "-"))
667             fclose(sinkfp);
668         if (ferror(sinkfp))
669         {
670             error(0, -1, "Message termination or close of BSMTP file failed");
671             return(FALSE);
672         }
673     }
674     else if (forward)
675     {
676                                 /* write message terminator */
677         if (SMTP_eom(ctl->smtp_socket) != SM_OK)
678         {
679             error(0, -1, "SMTP listener refused delivery");
680             return(FALSE);
681         }
682     }
683
684     return(TRUE);
685 }
686
687 /* sink.c ends here */