2 * transact.c -- transaction primitives for the fetchmail driver loop
4 * Copyright 2001 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
13 #include <ctype.h> /* isspace() */
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
20 #if defined(HAVE_UNISTD_H)
23 #if defined(HAVE_STDARG_H)
29 #ifdef HAVE_NET_SOCKET_H
30 #include <net/socket.h>
36 #include "fetchmail.h"
38 int mytimeout; /* value of nonreponse timeout */
39 int suppress_tags; /* emit tags? */
40 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
45 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
47 static int accept_count, reject_count;
48 static struct method *protocol;
50 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
51 /* add given name to xmit_names if it matches declared localnames */
52 /* name: name to map */
53 /* ctl: list of permissible aliases */
54 /* xmit_names: list of recipient names parsed out */
59 lname = idpair_find(&ctl->localnames, name+off);
60 if (!lname && ctl->wildcard)
63 if (lname != (char *)NULL)
65 if (outlevel >= O_DEBUG)
66 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
67 save_str(xmit_names, lname, XMIT_ACCEPT);
72 static void find_server_names(const char *hdr,
74 struct idlist **xmit_names)
75 /* parse names out of a RFC822 header into an ID list */
76 /* hdr: RFC822 header in question */
77 /* ctl: list of permissible aliases */
78 /* xmit_names: list of recipient names parsed out */
80 if (hdr == (char *)NULL)
86 for (cp = nxtaddr((const unsigned char *)hdr);
93 * Handle empty address from a To: header containing only
100 * If the name of the user begins with a qmail virtual
101 * domain prefix, ignore the prefix. Doing this here
102 * means qvirtual will work either with ordinary name
103 * mapping or with a localdomains option.
105 if (ctl->server.qvirtual)
107 int sl = strlen(ctl->server.qvirtual);
109 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
113 if ((atsign = strchr((char *)cp, '@'))) {
117 * Does a trailing segment of the hostname match something
118 * on the localdomains list? If so, save the whole name
121 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
124 rhs = atsign + (strlen(atsign) - strlen((char *)idp->id));
126 (rhs[-1] == '.' || rhs[-1] == '@') &&
127 strcasecmp(rhs, (char *)idp->id) == 0)
129 if (outlevel >= O_DEBUG)
130 report(stdout, GT_("passed through %s matching %s\n"),
132 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
138 /* if we matched a local domain, idp != NULL */
142 * Check to see if the right-hand part is an alias
143 * or MX equivalent of the mailserver. If it's
144 * not, skip this name. If it is, we'll keep
145 * going and try to find a mapping to a client name.
147 if (!is_host_alias(atsign+1, ctl))
149 save_str(xmit_names, cp, XMIT_REJECT);
155 map_name(cp, ctl, xmit_names);
163 * Return zero on a syntactically invalid address, nz on a valid one.
165 * This used to be strchr(a, '.'), but it turns out that lines like this
167 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
168 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
170 * are not uncommon. So now we just check that the following token is
171 * not itself an email address.
173 #define VALID_ADDRESS(a) !strchr(a, '@')
175 static char *parse_received(struct query *ctl, char *bufp)
176 /* try to extract real address from the Received line */
177 /* If a valid Received: line is found, we return the full address in
178 * a buffer which can be parsed from nxtaddr(). This is to ansure that
179 * the local domain part of the address can be passed along in
180 * find_server_names() if it contains one.
181 * Note: We should return a dummy header containing the address
182 * which makes nxtaddr() behave correctly.
185 char *base, *ok = (char *)NULL;
186 static char rbuf[HOSTLEN + USERNAMELEN + 4];
188 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
191 * Try to extract the real envelope addressee. We look here
192 * specifically for the mailserver's Received line.
193 * Note: this will only work for sendmail, or an MTA that
194 * shares sendmail's convention for embedding the envelope
195 * address in the Received line. Sendmail itself only
196 * does this when the mail has a single recipient.
198 if (outlevel >= O_DEBUG)
199 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
201 /* search for whitepace-surrounded "by" followed by valid address */
202 for (base = bufp; ; base = ok + 2)
204 if (!(ok = strstr(base, "by")))
206 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
212 /* extract space-delimited token after "by" */
213 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
216 for (; *sp && !isspace((unsigned char)*sp); sp++)
220 /* look for valid address */
221 if (VALID_ADDRESS(rbuf))
224 ok = sp - 1; /* arrange to skip this token */
230 * If it's a DNS name of the mail server, look for the
231 * recipient name after a following "for". Otherwise
234 if (is_host_alias(rbuf, ctl))
236 if (outlevel >= O_DEBUG)
238 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
242 if (outlevel >= O_DEBUG)
244 GT_("line rejected, %s is not an alias of the mailserver\n"),
249 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
250 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
252 if (!(ok = strstr(base, "for")))
254 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
260 /* extract space-delimited token after "for" */
261 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
264 for (; !isspace((unsigned char)*sp); sp++)
268 if (strchr(rbuf, '@'))
271 ok = sp - 1; /* arrange to skip this token */
276 flag want_gt = FALSE;
279 /* char after "for" could be space or a continuation newline */
280 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
283 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
284 RBUF_WRITE(' '); /* with nxtaddr()... */
290 while (*sp == '@') /* skip routes */
291 while (*sp && *sp++ != ':')
294 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
296 if (!isspace((unsigned char)*sp))
303 /* uh oh -- whitespace here can't be right! */
309 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
317 if (outlevel >= O_DEBUG)
318 report(stdout, GT_("no Received address found\n"));
323 if (outlevel >= O_DEBUG) {
324 char *lf = rbuf + strlen(rbuf)-1;
326 if (outlevel >= O_DEBUG)
327 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
334 /* shared by readheaders and readbody */
335 static int sizeticker;
337 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
338 || ((s)[0] == '\n' && (s)[1] == '\0'))
340 static int end_of_header (const char *s)
341 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
345 return (s[0] == '\n' && s[1] == '\0');
348 int readheaders(int sock,
353 flag *suppress_readbody)
354 /* read message headers and ship to SMTP or MDA */
355 /* sock: to which the server is connected */
356 /* fetchlen: length of message according to fetch response */
357 /* reallen: length of message according to getsizes */
358 /* ctl: query control record */
359 /* num: index of message */
360 /* suppress_readbody: whether call to readbody() should be supressed */
365 struct addrblk *next;
367 struct addrblk *to_addrchain = NULL;
368 struct addrblk **to_chainptr = &to_addrchain;
369 struct addrblk *resent_to_addrchain = NULL;
370 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
372 char buf[MSGBUFSIZE+1];
373 int from_offs, reply_to_offs, resent_from_offs;
374 int app_from_offs, sender_offs, resent_sender_offs;
376 char *received_for, *rcv, *cp;
377 static char *delivered_to = NULL;
378 int n, oldlen, ch, remaining, skipcount;
381 flag no_local_matches = FALSE;
383 int olderrs, good_addresses, bad_addresses;
384 int retain_mail = 0, refuse_mail = 0;
385 flag already_has_return_path = FALSE;
389 msgblk.return_path[0] = '\0';
390 olderrs = ctl->errcount;
392 /* read message headers */
393 msgblk.reallen = reallen;
396 * We used to free the header block unconditionally at the end of
397 * readheaders, but it turns out that if close_sink() hits an error
398 * condition the code for sending bouncemail will actually look
399 * at the freed storage and coredump...
402 free(msgblk.headers);
403 free_str_list(&msgblk.recipients);
407 /* initially, no message digest */
408 memset(ctl->digest, '\0', sizeof(ctl->digest));
410 msgblk.headers = received_for = delivered_to = NULL;
411 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
412 sender_offs = resent_sender_offs = env_offs = -1;
418 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
421 int overlong = FALSE; /* XXX FIXME: this is unused */
423 line = xmalloc(sizeof(buf));
430 set_timeout(mytimeout);
431 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
434 free(msgblk.headers);
435 msgblk.headers = NULL;
441 * Smash out any NULs, they could wreak havoc later on.
442 * Some network stacks seem to generate these at random,
443 * especially (according to reports) at the beginning of the
444 * first read. NULs are illegal in RFC822 format.
446 for (sp = tp = buf; sp < buf + n; sp++)
459 * Try to gracefully handle the case where the length of a
460 * line exceeds MSGBUFSIZE.
462 if (n && buf[n-1] != '\n')
465 rline = (char *) realloc(line, linelen + 1);
472 memcpy(line + linelen - n, buf, n);
473 line[linelen] = '\0';
474 ch = ' '; /* So the next iteration starts */
478 /* lines may not be properly CRLF terminated; fix this for qmail */
479 /* we don't want to overflow the buffer here */
480 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
483 rline = (char *) realloc(line, linelen + 2);
490 memcpy(line + linelen - n, buf, n - 1);
491 tcp = line + linelen - 1;
500 rline = (char *) realloc(line, linelen + 1);
507 memcpy(line + linelen - n, buf, n + 1);
510 /* check for end of headers */
511 if (end_of_header(line))
513 if (linelen != strlen (line))
516 goto process_headers;
520 * Check for end of message immediately. If one of your folders
521 * has been mangled, the delimiter may occur directly after the
524 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
526 if (outlevel > O_SILENT)
528 GT_("message delimiter found while scanning headers\n"));
529 if (suppress_readbody)
530 *suppress_readbody = TRUE;
531 if (linelen != strlen (line))
534 goto process_headers;
538 * At least one brain-dead website (netmind.com) is known to
539 * send out robotmail that's missing the RFC822 delimiter blank
540 * line before the body! Without this check fetchmail segfaults.
541 * With it, we treat such messages as spam and refuse them.
543 if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
545 if (linelen != strlen (line))
547 if (outlevel > O_SILENT)
549 GT_("incorrect header line found while scanning headers\n"));
550 if (outlevel >= O_VERBOSE)
551 report (stdout, GT_("line: %s"), line);
555 /* check for RFC822 continuations */
556 set_timeout(mytimeout);
560 (ch == ' ' || ch == '\t'); /* continuation to next line? */
562 /* write the message size dots */
563 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
565 sizeticker += linelen;
566 while (sizeticker >= SIZETICKER)
568 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
573 sizeticker -= SIZETICKER;
577 * Decode MIME encoded headers. We MUST do this before
578 * looking at the Content-Type / Content-Transfer-Encoding
579 * headers (RFC 2046).
581 if ( ctl->mimedecode )
585 /* the line is now shorter. So we retrace back till we find our terminating
586 * combination \n\0, we move backwards to make sure that we don't catch som
587 * \n\0 stored in the decoded part of the message */
588 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
589 if(tcp > line) linelen = tcp - line;
593 /* skip processing if we are going to retain or refuse this mail */
594 if (retain_mail || refuse_mail)
600 /* we see an ordinary (non-header, non-message-delimiter line */
601 if (linelen != strlen (line))
605 * The University of Washington IMAP server (the reference
606 * implementation of IMAP4 written by Mark Crispin) relies
607 * on being able to keep base-UID information in a special
608 * message at the head of the mailbox. This message should
609 * neither be deleted nor forwarded.
613 * We disable this check under POP2 because there's no way to
614 * prevent deletion of the message. So at least we ought to
615 * forward it to the user so he or she will have some clue
616 * that things have gone awry.
619 if (strncmp(protocol->service, "pop2", 4))
620 #else /* INET6_ENABLE */
621 if (protocol->port != 109)
622 #endif /* INET6_ENABLE */
623 #endif /* POP2_ENABLE */
624 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
631 * This code prevents fetchmail from becoming an accessory after
632 * the fact to upstream sendmails with the `E' option on. It also
633 * copes with certain brain-dead POP servers (like NT's) that pass
634 * through Unix from_ lines.
636 * Either of these bugs can result in a non-RFC822 line at the
637 * beginning of the headers. If fetchmail just passes it
638 * through, the client listener may think the message has *no*
639 * headers (since the first) line it sees doesn't look
640 * RFC822-conformant) and fake up a set.
642 * What the user would see in this case is bogus (synthesized)
643 * headers, followed by a blank line, followed by the >From,
644 * followed by the real headers, followed by a blank line,
647 * We forestall this lossage by tossing anything that looks
648 * like an escaped or passed-through From_ line in headers.
649 * These aren't RFC822 so our conscience is clear...
651 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
658 * We remove all Delivered-To: headers.
660 * This is to avoid false mail loops messages when delivering
661 * local messages to and from a Postfix/qmail mailserver.
663 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
673 * If we see a Status line, it may have been inserted by an MUA
674 * on the mail host, or it may have been inserted by the server
675 * program after the headers in the transaction stream. This
676 * can actually hose some new-mail notifiers such as xbuffy,
677 * which assumes any Status line came from a *local* MDA and
678 * therefore indicates that the message has been seen.
680 * Some buggy POP servers (including at least the 3.3(20)
681 * version of the one distributed with IMAP) insert empty
682 * Status lines in the transaction stream; we'll chuck those
683 * unconditionally. Nonempty ones get chucked if the user
684 * turns on the dropstatus flag.
689 if (!strncasecmp(line, "Status:", 7))
691 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
696 while (*cp && isspace((unsigned char)*cp)) cp++;
697 if (!*cp || ctl->dropstatus)
706 line = reply_hack(line, ctl->server.truename, &linelen);
709 * OK, this is messy. If we're forwarding by SMTP, it's the
710 * SMTP-receiver's job (according to RFC821, page 22, section
711 * 4.1.1) to generate a Return-Path line on final delivery.
712 * The trouble is, we've already got one because the
713 * mailserver's SMTP thought *it* was responsible for final
716 * Stash away the contents of Return-Path (as modified by reply_hack)
717 * for use in generating MAIL FROM later on, then prevent the header
718 * from being saved with the others. In effect, we strip it off here.
720 * If the SMTP server conforms to the standards, and fetchmail gets the
721 * envelope sender from the Return-Path, the new Return-Path should be
722 * exactly the same as the original one.
724 * We do *not* want to ignore empty Return-Path headers. These should
725 * be passed through as a way of indicating that a message should
726 * not trigger bounces if delivery fails. What we *do* need to do is
727 * make sure we never try to rewrite such a blank Return-Path. We
728 * handle this with a check for <> in the rewrite logic above.
730 * Also, if an email has multiple Return-Path: headers, we only
731 * read the first occurance, as some spam email has more than one
735 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
737 already_has_return_path = TRUE;
738 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
740 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
741 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
751 msgblk.headers = xmalloc(oldlen + 1);
752 (void) memcpy(msgblk.headers, line, linelen);
753 msgblk.headers[oldlen] = '\0';
755 line = msgblk.headers;
762 newlen = oldlen + linelen;
763 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
764 if (newhdrs == NULL) {
768 msgblk.headers = newhdrs;
769 memcpy(msgblk.headers + oldlen, line, linelen);
770 msgblk.headers[newlen] = '\0';
772 line = msgblk.headers + oldlen;
776 /* find offsets of various special headers */
777 if (!strncasecmp("From:", line, 5))
778 from_offs = (line - msgblk.headers);
779 else if (!strncasecmp("Reply-To:", line, 9))
780 reply_to_offs = (line - msgblk.headers);
781 else if (!strncasecmp("Resent-From:", line, 12))
782 resent_from_offs = (line - msgblk.headers);
783 else if (!strncasecmp("Apparently-From:", line, 16))
784 app_from_offs = (line - msgblk.headers);
786 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
788 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
789 * that Sender: *doesn't* have to be a working email address.
791 * The definition of the Sender header in RFC822 says, in
792 * part, "The Sender mailbox specification includes a word
793 * sequence which must correspond to a specific agent (i.e., a
794 * human user or a computer program) rather than a standard
795 * address." That implies that the contents of the Sender
796 * field don't need to be a legal email address at all So
797 * ignore any Sender or Resent-Sender lines unless they
800 * (RFC2822 says the contents of Sender must be a valid mailbox
801 * address, which is also what RFC822 4.4.4 implies.)
803 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
804 sender_offs = (line - msgblk.headers);
805 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
806 resent_sender_offs = (line - msgblk.headers);
809 else if (!strncasecmp("Message-Id:", line, 11))
811 if (ctl->server.uidl)
815 line[IDLEN+12] = 0; /* prevent stack overflow */
816 sscanf(line+12, "%s", id);
817 if (!str_find( &ctl->newsaved, num))
819 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
820 new->val.status.num = num;
824 #endif /* __UNUSED__ */
826 /* if multidrop is on, gather addressee headers */
829 if (!strncasecmp("To:", line, 3)
830 || !strncasecmp("Cc:", line, 3)
831 || !strncasecmp("Bcc:", line, 4)
832 || !strncasecmp("Apparently-To:", line, 14))
834 *to_chainptr = xmalloc(sizeof(struct addrblk));
835 (*to_chainptr)->offset = (line - msgblk.headers);
836 to_chainptr = &(*to_chainptr)->next;
840 else if (!strncasecmp("Resent-To:", line, 10)
841 || !strncasecmp("Resent-Cc:", line, 10)
842 || !strncasecmp("Resent-Bcc:", line, 11))
844 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
845 (*resent_to_chainptr)->offset = (line - msgblk.headers);
846 resent_to_chainptr = &(*resent_to_chainptr)->next;
847 *resent_to_chainptr = NULL;
850 else if (ctl->server.envelope != STRING_DISABLED)
852 if (ctl->server.envelope
853 && strcasecmp(ctl->server.envelope, "Received"))
855 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
857 strlen(ctl->server.envelope)))
859 if (skipcount++ < ctl->server.envskip)
861 env_offs = (line - msgblk.headers);
864 else if (!received_for && !strncasecmp("Received:", line, 9))
866 if (skipcount++ < ctl->server.envskip)
868 received_for = parse_received(ctl, line);
878 free(msgblk.headers);
879 msgblk.headers = NULL;
885 * This is the duplicate-message killer code.
887 * When mail delivered to a multidrop mailbox on the server is
888 * addressed to multiple people on the client machine, there will
889 * be one copy left in the box for each recipient. This is not a
890 * problem if we have the actual recipient address to dispatch on
891 * (e.g. because we've mined it out of sendmail trace headers, or
892 * a qmail Delivered-To line, or a declared sender envelope line).
894 * But if we're mining addressees out of the To/Cc/Bcc fields, and
895 * if the mail is addressed to N people, each recipient will
896 * get N copies. This is bad when N > 1.
898 * Foil this by suppressing all but one copy of a message with a
899 * given set of headers.
901 * Note: This implementation only catches runs of successive
902 * messages with the same ID, but that should be good
903 * enough. A more general implementation would have to store
904 * ever-growing lists of seen message-IDs; in a long-running
905 * daemon this would turn into a memory leak even if the
906 * implementation were perfect.
908 * Don't mess with this code casually. It would be way too easy
909 * to break it in a way that blackholed mail. Better to pass
910 * the occasional duplicate than to do that...
917 MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
918 MD5Final(ctl->digest, &context);
920 if (!received_for && env_offs == -1 && !delivered_to)
923 * Hmmm...can MD5 ever yield all zeroes as a hash value?
924 * If so there is a one in 18-quadrillion chance this
925 * code will incorrectly nuke the first message.
927 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
930 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
934 * Hack time. If the first line of the message was blank, with no headers
935 * (this happens occasionally due to bad gatewaying software) cons up
936 * a set of fake headers.
938 * If you modify the fake header template below, be sure you don't
939 * make either From or To address @-less, otherwise the reply_hack
940 * logic will do bad things.
942 if (msgblk.headers == (char *)NULL)
944 snprintf(buf, sizeof(buf),
945 "From: FETCHMAIL-DAEMON\r\n"
947 "Subject: Headerless mail from %s's mailbox on %s\r\n",
948 user, fetchmailhost, ctl->remotename, ctl->server.truename);
949 msgblk.headers = xstrdup(buf);
953 * We can now process message headers before reading the text.
954 * In fact we have to, as this will tell us where to forward to.
957 /* Check for MIME headers indicating possible 8-bit data */
958 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
961 if (ctl->server.sdps && sdps_envfrom)
963 /* We have the real envelope return-path, stored out of band by
964 * SDPS - that's more accurate than any header is going to be.
966 strcpy(msgblk.return_path, sdps_envfrom);
969 #endif /* SDPS_ENABLE */
971 * If there is a Return-Path address on the message, this was
972 * almost certainly the MAIL FROM address given the originating
973 * sendmail. This is the best thing to use for logging the
974 * message origin (it sets up the right behavior for bounces and
975 * mailing lists). Otherwise, fall down to the next available
976 * envelope address (which is the most probable real sender).
977 * *** The order is important! ***
978 * This is especially useful when receiving mailing list
979 * messages in multidrop mode. if a local address doesn't
980 * exist, the bounce message won't be returned blindly to the
981 * author or to the list itself but rather to the list manager
982 * (ex: specified by "Sender:") which is much less annoying. This
983 * is true for most mailing list packages.
985 if( !msgblk.return_path[0] ){
987 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
988 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
989 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
990 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
991 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
992 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
993 /* multi-line MAIL FROM addresses confuse SMTP terribly */
994 if (ap && !strchr(ap, '\n')) {
995 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
996 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1000 /* cons up a list of local recipients */
1001 msgblk.recipients = (struct idlist *)NULL;
1002 accept_count = reject_count = 0;
1003 /* is this a multidrop box? */
1007 if (ctl->server.sdps && sdps_envto)
1009 /* We have the real envelope recipient, stored out of band by
1010 * SDPS - that's more accurate than any header is going to be.
1012 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1015 #endif /* SDPS_ENABLE */
1016 if (env_offs > -1) /* We have the actual envelope addressee */
1017 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1018 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1019 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1021 find_server_names(delivered_to, ctl, &msgblk.recipients);
1023 delivered_to = NULL;
1025 else if (received_for)
1027 * We have the Received for addressee.
1028 * It has to be a mailserver address, or we
1029 * wouldn't have got here.
1030 * We use find_server_names() to let local
1031 * hostnames go through.
1033 find_server_names(received_for, ctl, &msgblk.recipients);
1037 * We haven't extracted the envelope address.
1038 * So check all the "Resent-To" header addresses if
1039 * they exist. If and only if they don't, consider
1040 * the "To" addresses.
1042 register struct addrblk *nextptr;
1043 if (resent_to_addrchain) {
1044 /* delete the "To" chain and substitute it
1045 * with the "Resent-To" list
1047 while (to_addrchain) {
1048 nextptr = to_addrchain->next;
1050 to_addrchain = nextptr;
1052 to_addrchain = resent_to_addrchain;
1053 resent_to_addrchain = NULL;
1055 /* now look for remaining adresses */
1056 while (to_addrchain) {
1057 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1058 nextptr = to_addrchain->next;
1060 to_addrchain = nextptr;
1065 no_local_matches = TRUE;
1066 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1067 if (outlevel >= O_DEBUG)
1069 GT_("no local matches, forwarding to %s\n"),
1073 else /* it's a single-drop box, use first localname */
1074 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1078 * Time to either address the message or decide we can't deliver it yet.
1080 if (ctl->errcount > olderrs) /* there were DNS errors above */
1082 if (outlevel >= O_DEBUG)
1084 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1085 free(msgblk.headers);
1086 msgblk.headers = NULL;
1087 free_str_list(&msgblk.recipients);
1088 return(PS_TRANSIENT);
1092 /* set up stuffline() so we can deliver the message body through it */
1093 if ((n = open_sink(ctl, &msgblk,
1094 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1096 free(msgblk.headers);
1097 msgblk.headers = NULL;
1098 free_str_list(&msgblk.recipients);
1105 * Some server/sendmail combinations cause problems when our
1106 * synthetic Received line is before the From header. Cope
1109 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1110 rcv = msgblk.headers;
1111 /* handle ">Received:" lines too */
1112 while (rcv > msgblk.headers && rcv[-1] != '\n')
1114 if (rcv > msgblk.headers)
1119 n = stuffline(ctl, msgblk.headers);
1122 if (!run.invisible && n != -1)
1124 /* utter any per-message Received information we need here */
1125 if (ctl->server.trueaddr) {
1126 snprintf(buf, sizeof(buf),
1127 "Received: from %s [%u.%u.%u.%u]\r\n",
1128 ctl->server.truename,
1129 (unsigned int)(unsigned char)ctl->server.trueaddr[0],
1130 (unsigned int)(unsigned char)ctl->server.trueaddr[1],
1131 (unsigned int)(unsigned char)ctl->server.trueaddr[2],
1132 (unsigned int)(unsigned char)ctl->server.trueaddr[3]);
1134 snprintf(buf, sizeof(buf),
1135 "Received: from %s\r\n", ctl->server.truename);
1137 n = stuffline(ctl, buf);
1141 * This header is technically invalid under RFC822.
1142 * POP3, IMAP, etc. are not legal mail-parameter values.
1144 snprintf(buf, sizeof(buf),
1145 "\tby %s with %s (fetchmail-%s",
1149 if (ctl->server.tracepolls)
1151 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1152 " polling %s account %s",
1153 ctl->server.pollname,
1156 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1157 n = stuffline(ctl, buf);
1161 if (good_addresses == 0)
1163 snprintf(buf+1, sizeof(buf)-1, "for %s (by default); ",
1164 rcpt_address (ctl, run.postmaster, 0));
1166 else if (good_addresses == 1)
1168 for (idp = msgblk.recipients; idp; idp = idp->next)
1169 if (idp->val.status.mark == XMIT_ACCEPT)
1170 break; /* only report first address */
1171 snprintf(buf+1, sizeof(buf)-1,
1172 "for %s", rcpt_address (ctl, idp->id, 1));
1173 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1175 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1180 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1182 n = stuffline(ctl, buf);
1188 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1192 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1194 free(msgblk.headers);
1195 msgblk.headers = NULL;
1196 free_str_list(&msgblk.recipients);
1199 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1202 /* write error notifications */
1203 if (no_local_matches || has_nuls || bad_addresses)
1206 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1209 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1210 if (no_local_matches)
1212 if (reject_count != 1)
1213 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1216 for (idp = msgblk.recipients; idp; idp = idp->next)
1217 if (idp->val.status.mark == XMIT_REJECT)
1219 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1220 GT_("recipient address %s didn't match any local name"), idp->id);
1226 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1227 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1228 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1229 GT_("message has embedded NULs"));
1234 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1235 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1236 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1237 GT_("SMTP listener rejected local recipient addresses: "));
1238 errlen = strlen(errhd);
1239 for (idp = msgblk.recipients; idp; idp = idp->next)
1240 if (idp->val.status.mark == XMIT_RCPTBAD)
1241 errlen += strlen(idp->id) + 2;
1243 xalloca(errmsg, char *, errlen+3);
1244 (void) strcpy(errmsg, errhd);
1245 for (idp = msgblk.recipients; idp; idp = idp->next)
1246 if (idp->val.status.mark == XMIT_RCPTBAD)
1248 strcat(errmsg, idp->id);
1250 strcat(errmsg, ", ");
1255 strcat(errmsg, "\r\n");
1257 /* ship out the error line */
1258 stuffline(ctl, errmsg);
1261 /* issue the delimiter line */
1266 stuffline(ctl, buf);
1271 int readbody(int sock, struct query *ctl, flag forward, int len)
1272 /* read and dispose of a message body presented on sock */
1273 /* ctl: query control record */
1274 /* sock: to which the server is connected */
1275 /* len: length of message */
1276 /* forward: TRUE to forward */
1279 unsigned char buf[MSGBUFSIZE+4];
1280 unsigned char *inbufp = buf;
1281 flag issoftline = FALSE;
1284 * Pass through the text lines in the body.
1286 * Yes, this wants to be ||, not &&. The problem is that in the most
1287 * important delimited protocol, POP3, the length is not reliable.
1288 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1289 * So, for delimited protocols we need to ignore the length here and
1290 * instead drop out of the loop with a break statement when we see
1291 * the message delimiter.
1293 while (protocol->delimited || len > 0)
1295 set_timeout(mytimeout);
1296 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1304 /* write the message size dots */
1307 sizeticker += linelen;
1308 while (sizeticker >= SIZETICKER)
1310 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
1315 sizeticker -= SIZETICKER;
1320 /* check for end of message */
1321 if (protocol->delimited && *inbufp == '.')
1323 if (EMPTYLINE(inbufp+1))
1326 msgblk.msglen--; /* subtract the size of the dot escape */
1329 msgblk.msglen += linelen;
1331 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1332 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1333 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1336 * Soft linebreak, but less than 200 bytes left in
1337 * input buffer. Rather than doing a buffer overrun,
1338 * ignore the soft linebreak, NL-terminate data and
1339 * deliver what we have now.
1340 * (Who writes lines longer than 2K anyway?)
1342 *inbufp = '\n'; *(inbufp+1) = '\0';
1347 /* ship out the text line */
1348 if (forward && (!issoftline))
1353 /* guard against very long lines */
1354 buf[MSGBUFSIZE+1] = '\r';
1355 buf[MSGBUFSIZE+2] = '\n';
1356 buf[MSGBUFSIZE+3] = '\0';
1358 n = stuffline(ctl, buf);
1362 report(stdout, GT_("writing message text\n"));
1366 else if (outlevel >= O_VERBOSE && !isafile(1))
1377 void init_transact(const struct method *proto)
1378 /* initialize state for the send and receive functions */
1381 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1382 protocol = (struct method *)proto;
1385 static void enshroud(char *buf)
1386 /* shroud a password in the given buffer */
1390 if (shroud[0] && (cp = strstr(buf, shroud)))
1394 sp = cp + strlen(shroud);
1402 #if defined(HAVE_STDARG_H)
1403 void gen_send(int sock, const char *fmt, ... )
1405 void gen_send(sock, fmt, va_alist)
1406 int sock; /* socket to which server is connected */
1407 const char *fmt; /* printf-style format */
1410 /* assemble command in printf(3) style and send to the server */
1412 char buf [MSGBUFSIZE+1];
1415 if (protocol->tagged && !suppress_tags)
1416 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1420 #if defined(HAVE_STDARG_H)
1425 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1428 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1429 SockWrite(sock, buf, strlen(buf));
1431 if (outlevel >= O_MONITOR)
1434 buf[strlen(buf)-2] = '\0';
1435 report(stdout, "%s> %s\n", protocol->name, buf);
1439 int gen_recv(sock, buf, size)
1440 /* get one line of input from the server */
1441 int sock; /* socket to which server is connected */
1442 char *buf; /* buffer to receive input */
1443 int size; /* length of buffer */
1445 int oldphase = phase; /* we don't have to be re-entrant */
1447 phase = SERVER_WAIT;
1448 set_timeout(mytimeout);
1449 if (SockRead(sock, buf, size) == -1)
1456 return(PS_IDLETIMEOUT);
1464 if (buf[strlen(buf)-1] == '\n')
1465 buf[strlen(buf)-1] = '\0';
1466 if (buf[strlen(buf)-1] == '\r')
1467 buf[strlen(buf)-1] = '\0';
1468 if (outlevel >= O_MONITOR)
1469 report(stdout, "%s< %s\n", protocol->name, buf);
1475 #if defined(HAVE_STDARG_H)
1476 int gen_transact(int sock, const char *fmt, ... )
1478 int gen_transact(int sock, fmt, va_alist)
1479 int sock; /* socket to which server is connected */
1480 const char *fmt; /* printf-style format */
1483 /* assemble command in printf(3) style, send to server, accept a response */
1486 char buf [MSGBUFSIZE+1];
1488 int oldphase = phase; /* we don't have to be re-entrant */
1490 phase = SERVER_WAIT;
1492 if (protocol->tagged && !suppress_tags)
1493 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1497 #if defined(HAVE_STDARG_H)
1502 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1505 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1506 if (SockWrite(sock, buf, strlen(buf)) < strlen(buf)) {
1507 /* short write, bail out */
1511 if (outlevel >= O_MONITOR)
1514 buf[strlen(buf)-2] = '\0';
1515 report(stdout, "%s> %s\n", protocol->name, buf);
1518 /* we presume this does its own response echoing */
1519 ok = (protocol->parse_response)(sock, buf);
1525 /* transact.c ends here */