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.
14 #endif /* HAVE_MEMORY_H */
15 #if defined(STDC_HEADERS)
18 #if defined(HAVE_UNISTD_H)
21 #if defined(HAVE_STDARG_H)
28 #ifdef HAVE_NET_SOCKET_H
29 #include <net/socket.h>
31 #include <sys/socket.h>
37 #include "fetchmail.h"
39 #define _FIX_INT_MIN(x) ((x) < INT_MIN ? INT_MIN : (x))
40 #define _FIX_INT_MAX(x) ((x) > INT_MAX ? INT_MAX : (x))
41 #define CAST_TO_INT(x) ((int)(_FIX_INT_MIN(_FIX_INT_MAX(x))))
42 #define UCAST_TO_INT(x) ((int)(_FIX_INT_MAX(x)))
44 /* global variables: please reinitialize them explicitly for proper
45 * working in daemon mode */
47 /* session variables initialized in init_transact() */
48 int suppress_tags = FALSE; /* emit tags? */
51 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
52 static const struct method *protocol;
53 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
55 /* session variables initialized in do_session() */
56 int mytimeout; /* value of nonreponse timeout */
58 /* mail variables initialized in readheaders() */
60 static int accept_count, reject_count;
62 /** add given address to xmit_names if it exactly matches a full address
63 * \returns nonzero if matched */
64 static int map_address(const char *addr, struct query *ctl, struct idlist **xmit_names)
68 lname = idpair_find(&ctl->localnames, addr);
70 if (outlevel >= O_DEBUG)
71 report(stdout, GT_("mapped address %s to local %s\n"), addr, lname);
72 save_str(xmit_names, lname, XMIT_ACCEPT);
78 /** add given name to xmit_names if it matches declared localnames */
79 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
80 /* name: name to map */
81 /* ctl: list of permissible aliases */
82 /* xmit_names: list of recipient names parsed out */
86 lname = idpair_find(&ctl->localnames, name);
87 if (!lname && ctl->wildcard)
90 if (lname != (char *)NULL)
92 if (outlevel >= O_DEBUG)
93 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
94 save_str(xmit_names, lname, XMIT_ACCEPT);
99 static void find_server_names(const char *hdr,
101 struct idlist **xmit_names)
102 /* parse names out of a RFC822 header into an ID list */
103 /* hdr: RFC822 header in question */
104 /* ctl: list of permissible aliases */
105 /* xmit_names: list of recipient names parsed out */
107 if (hdr == (char *)NULL)
113 for (cp = nxtaddr(hdr); cp != NULL; cp = nxtaddr(NULL))
118 * Handle empty address from a To: header containing only
125 * If the name of the user begins with a qmail virtual
126 * domain prefix, ignore the prefix. Doing this here
127 * means qvirtual will work either with ordinary name
128 * mapping or with a localdomains option.
130 if (ctl->server.qvirtual)
132 int sl = strlen(ctl->server.qvirtual);
134 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
138 if ((atsign = strchr((char *)cp, '@'))) {
141 /* try to match full address first, this takes
142 * precedence over localdomains and alias mappings */
143 if (map_address(cp, ctl, xmit_names))
147 * Does a trailing segment of the hostname match something
148 * on the localdomains list? If so, save the whole name
151 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
154 rhs = atsign + (strlen(atsign) - strlen(idp->id));
156 (rhs[-1] == '.' || rhs[-1] == '@') &&
157 strcasecmp(rhs, idp->id) == 0)
159 if (outlevel >= O_DEBUG)
160 report(stdout, GT_("passed through %s matching %s\n"),
162 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
168 /* if we matched a local domain, idp != NULL */
172 * Check to see if the right-hand part is an alias
173 * or MX equivalent of the mailserver. If it's
174 * not, skip this name. If it is, we'll keep
175 * going and try to find a mapping to a client name.
177 if (!is_host_alias(atsign+1, ctl, &ai0))
179 save_str(xmit_names, cp, XMIT_REJECT);
185 map_name(cp, ctl, xmit_names);
193 * Return zero on a syntactically invalid address, nz on a valid one.
195 * This used to be strchr(a, '.'), but it turns out that lines like this
197 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
198 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
200 * are not uncommon. So now we just check that the following token is
201 * not itself an email address.
203 #define VALID_ADDRESS(a) !strchr(a, '@')
205 static char *parse_received(struct query *ctl, char *bufp)
206 /* try to extract real address from the Received line */
207 /* If a valid Received: line is found, we return the full address in
208 * a buffer which can be parsed from nxtaddr(). This is to ansure that
209 * the local domain part of the address can be passed along in
210 * find_server_names() if it contains one.
211 * Note: We should return a dummy header containing the address
212 * which makes nxtaddr() behave correctly.
215 char *base, *ok = (char *)NULL;
216 static char rbuf[HOSTLEN + USERNAMELEN + 4];
217 struct addrinfo *ai0;
219 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
222 * Try to extract the real envelope addressee. We look here
223 * specifically for the mailserver's Received line.
224 * Note: this will only work for sendmail, or an MTA that
225 * shares sendmail's convention for embedding the envelope
226 * address in the Received line. Sendmail itself only
227 * does this when the mail has a single recipient.
229 if (outlevel >= O_DEBUG)
230 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
232 /* search for whitepace-surrounded "by" followed by valid address */
233 for (base = bufp; ; base = ok + 2)
235 if (!(ok = strstr(base, "by")))
237 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
243 /* extract space-delimited token after "by" */
244 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
247 for (; *sp && !isspace((unsigned char)*sp); sp++)
251 /* look for valid address */
252 if (VALID_ADDRESS(rbuf))
255 ok = sp - 1; /* arrange to skip this token */
261 * If it's a DNS name of the mail server, look for the
262 * recipient name after a following "for". Otherwise
265 if (is_host_alias(rbuf, ctl, &ai0))
267 if (outlevel >= O_DEBUG)
269 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
273 if (outlevel >= O_DEBUG)
275 GT_("line rejected, %s is not an alias of the mailserver\n"),
280 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
281 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
283 if (!(ok = strstr(base, "for")))
285 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
291 /* extract space-delimited token after "for" */
292 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
295 for (; !isspace((unsigned char)*sp); sp++)
299 if (strchr(rbuf, '@'))
302 ok = sp - 1; /* arrange to skip this token */
307 flag want_gt = FALSE;
310 /* char after "for" could be space or a continuation newline */
311 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
314 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
315 RBUF_WRITE(' '); /* with nxtaddr()... */
321 while (*sp == '@') /* skip routes */
322 while (*sp && *sp++ != ':')
325 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
327 if (!isspace((unsigned char)*sp))
334 /* uh oh -- whitespace here can't be right! */
340 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
348 if (outlevel >= O_DEBUG)
349 report(stdout, GT_("no Received address found\n"));
354 if (outlevel >= O_DEBUG) {
355 char *lf = rbuf + strlen(rbuf)-1;
357 if (outlevel >= O_DEBUG)
358 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
365 /* shared by readheaders and readbody */
366 static int sizeticker;
368 /** Print ticker based on a amount of data transferred of \a bytes.
369 * Increments \a *tickervar by \a bytes, and if it exceeds
370 * \a SIZETICKER, print a dot and reduce *tickervar by \a SIZETICKER. */
371 static void print_ticker(int *tickervar, int bytes)
374 while (*tickervar >= SIZETICKER)
381 *tickervar -= SIZETICKER;
385 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
386 || ((s)[0] == '\n' && (s)[1] == '\0'))
388 static int end_of_header (const char *s)
389 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
393 return (s[0] == '\n' && s[1] == '\0');
396 int readheaders(int sock,
401 flag *suppress_readbody)
402 /* read message headers and ship to SMTP or MDA */
403 /* sock: to which the server is connected */
404 /* fetchlen: length of message according to fetch response */
405 /* reallen: length of message according to getsizes */
406 /* ctl: query control record */
407 /* num: index of message */
408 /* suppress_readbody: whether call to readbody() should be supressed */
413 struct addrblk *next;
415 struct addrblk *to_addrchain = NULL;
416 struct addrblk **to_chainptr = &to_addrchain;
417 struct addrblk *resent_to_addrchain = NULL;
418 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
420 char buf[MSGBUFSIZE+1];
421 int from_offs, reply_to_offs, resent_from_offs;
422 int app_from_offs, sender_offs, resent_sender_offs;
424 char *received_for, *rcv, *cp;
425 static char *delivered_to = NULL;
426 int n, oldlen, ch, remaining, skipcount;
428 int delivered_to_count;
430 flag no_local_matches = FALSE;
432 int olderrs, good_addresses, bad_addresses;
433 int retain_mail = 0, refuse_mail = 0;
434 flag already_has_return_path = FALSE;
438 msgblk.return_path[0] = '\0';
439 olderrs = ctl->errcount;
441 /* read message headers */
442 msgblk.reallen = reallen;
445 * We used to free the header block unconditionally at the end of
446 * readheaders, but it turns out that if close_sink() hits an error
447 * condition the code for sending bouncemail will actually look
448 * at the freed storage and coredump...
450 xfree(msgblk.headers);
451 free_str_list(&msgblk.recipients);
454 /* initially, no message digest */
455 memset(ctl->digest, '\0', sizeof(ctl->digest));
458 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
459 sender_offs = resent_sender_offs = env_offs = -1;
463 delivered_to_count = 0;
466 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
470 line = (char *)xmalloc(sizeof(buf));
477 set_timeout(mytimeout);
478 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
486 * Smash out any NULs, they could wreak havoc later on.
487 * Some network stacks seem to generate these at random,
488 * especially (according to reports) at the beginning of the
489 * first read. NULs are illegal in RFC822 format.
491 for (sp = tp = buf; sp < buf + n; sp++)
504 * Try to gracefully handle the case where the length of a
505 * line exceeds MSGBUFSIZE.
507 if (n && buf[n-1] != '\n')
509 rline = (char *) realloc(line, linelen + 1);
516 memcpy(line + linelen - n, buf, n);
517 line[linelen] = '\0';
518 ch = ' '; /* So the next iteration starts */
522 /* lines may not be properly CRLF terminated; fix this for qmail */
523 /* we don't want to overflow the buffer here */
524 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
527 rline = (char *) realloc(line, linelen + 2);
534 memcpy(line + linelen - n, buf, n - 1);
535 tcp = line + linelen - 1;
539 /* n++; - not used later on */
544 rline = (char *) realloc(line, linelen + 1);
551 memcpy(line + linelen - n, buf, n + 1);
554 /* check for end of headers */
555 if (end_of_header(line))
558 if (linelen != strlen (line))
561 goto process_headers;
565 * Check for end of message immediately. If one of your folders
566 * has been mangled, the delimiter may occur directly after the
569 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
571 if (suppress_readbody)
572 *suppress_readbody = TRUE;
573 goto eoh; /* above */
577 * At least one brain-dead website (netmind.com) is known to
578 * send out robotmail that's missing the RFC822 delimiter blank
579 * line before the body! Without this check fetchmail segfaults.
580 * With it, we treat such messages as spam and refuse them.
582 * Frederic Marchal reported in February 2006 that hotmail
583 * or something improperly wrapped a very long TO header
584 * (wrapped without inserting whitespace in the continuation
585 * line) and found that this code thus refused a message
586 * that should have been delivered.
588 * XXX FIXME: we should probably wrap the message up as
589 * message/rfc822 attachment and forward to postmaster (Rob
593 && !ctl->server.badheader == BHACCEPT
594 && !isspace((unsigned char)line[0])
595 && !strchr(line, ':'))
597 if (linelen != strlen (line))
599 if (outlevel > O_SILENT)
601 GT_("incorrect header line found - see manpage for bad-header option\n"));
602 if (outlevel >= O_VERBOSE)
603 report (stdout, GT_("line: %s"), line);
607 /* check for RFC822 continuations */
608 set_timeout(mytimeout);
612 (ch == ' ' || ch == '\t'); /* continuation to next line? */
614 /* write the message size dots */
615 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
617 print_ticker(&sizeticker, linelen);
621 * Decode MIME encoded headers. We MUST do this before
622 * looking at the Content-Type / Content-Transfer-Encoding
623 * headers (RFC 2046).
625 if ( ctl->mimedecode )
629 /* the line is now shorter. So we retrace back till we find
630 * our terminating combination \n\0, we move backwards to
631 * make sure that we don't catch some \n\0 stored in the
632 * decoded part of the message */
633 for (tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--) { }
634 if (tcp > line) linelen = tcp - line;
638 /* skip processing if we are going to retain or refuse this mail */
639 if (retain_mail || refuse_mail)
645 /* we see an ordinary (non-header, non-message-delimiter) line */
646 if (linelen != strlen (line))
650 * The University of Washington IMAP server (the reference
651 * implementation of IMAP4 written by Mark Crispin) relies
652 * on being able to keep base-UID information in a special
653 * message at the head of the mailbox. This message should
654 * neither be deleted nor forwarded.
656 * An example for such a message is (keep this in so people
657 * find it when looking where the special code is to handle the
660 * From MAILER-DAEMON Wed Nov 23 11:38:42 2005
661 * Date: 23 Nov 2005 11:38:42 +0100
662 * From: Mail System Internal Data <MAILER-DAEMON@mail.example.org>
663 * Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
664 * Message-ID: <1132742322@mail.example.org>
665 * X-IMAP: 1132742306 0000000001
668 * This text is part of the internal format of your mail folder, and is not
669 * a real message. It is created automatically by the mail system software.
670 * If deleted, important folder data will be lost, and it will be re-created
671 * with the data reset to initial values.
673 * This message is only visible if a POP3 server that is unaware
674 * of these UWIMAP messages is used besides UWIMAP or PINE.
676 * We will just check if the first message in the mailbox has an
681 * We disable this check under POP2 because there's no way to
682 * prevent deletion of the message. So at least we ought to
683 * forward it to the user so he or she will have some clue
684 * that things have gone awry.
686 if (servport("pop2") != servport(protocol->service))
687 #endif /* POP2_ENABLE */
688 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
695 * This code prevents fetchmail from becoming an accessory after
696 * the fact to upstream sendmails with the `E' option on. It also
697 * copes with certain brain-dead POP servers (like NT's) that pass
698 * through Unix from_ lines.
700 * Either of these bugs can result in a non-RFC822 line at the
701 * beginning of the headers. If fetchmail just passes it
702 * through, the client listener may think the message has *no*
703 * headers (since the first) line it sees doesn't look
704 * RFC822-conformant) and fake up a set.
706 * What the user would see in this case is bogus (synthesized)
707 * headers, followed by a blank line, followed by the >From,
708 * followed by the real headers, followed by a blank line,
711 * We forestall this lossage by tossing anything that looks
712 * like an escaped or passed-through From_ line in headers.
713 * These aren't RFC822 so our conscience is clear...
715 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
722 * We remove all Delivered-To: headers if dropdelivered is set
723 * - special care must be taken if Delivered-To: is also used
724 * as envelope at the same time.
726 * This is to avoid false mail loops errors when delivering
727 * local messages to and from a Postfix or qmail mailserver.
729 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
732 ctl->server.envelope == STRING_DISABLED ||
733 !ctl->server.envelope ||
734 strcasecmp(ctl->server.envelope, "Delivered-To") ||
735 delivered_to_count != ctl->server.envskip)
739 delivered_to_count++;
744 * If we see a Status line, it may have been inserted by an MUA
745 * on the mail host, or it may have been inserted by the server
746 * program after the headers in the transaction stream. This
747 * can actually hose some new-mail notifiers such as xbuffy,
748 * which assumes any Status line came from a *local* MDA and
749 * therefore indicates that the message has been seen.
751 * Some buggy POP servers (including at least the 3.3(20)
752 * version of the one distributed with IMAP) insert empty
753 * Status lines in the transaction stream; we'll chuck those
754 * unconditionally. Nonempty ones get chucked if the user
755 * turns on the dropstatus flag.
760 if (!strncasecmp(line, "Status:", 7))
762 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
767 while (*tcp && isspace((unsigned char)*tcp)) tcp++;
768 if (!*tcp || ctl->dropstatus)
777 line = reply_hack(line, ctl->server.truename, &linelen);
780 * OK, this is messy. If we're forwarding by SMTP, it's the
781 * SMTP-receiver's job (according to RFC821, page 22, section
782 * 4.1.1) to generate a Return-Path line on final delivery.
783 * The trouble is, we've already got one because the
784 * mailserver's SMTP thought *it* was responsible for final
787 * Stash away the contents of Return-Path (as modified by reply_hack)
788 * for use in generating MAIL FROM later on, then prevent the header
789 * from being saved with the others. In effect, we strip it off here.
791 * If the SMTP server conforms to the standards, and fetchmail gets the
792 * envelope sender from the Return-Path, the new Return-Path should be
793 * exactly the same as the original one.
795 * We do *not* want to ignore empty Return-Path headers. These should
796 * be passed through as a way of indicating that a message should
797 * not trigger bounces if delivery fails. What we *do* need to do is
798 * make sure we never try to rewrite such a blank Return-Path. We
799 * handle this with a check for <> in the rewrite logic above.
801 * Also, if an email has multiple Return-Path: headers, we only
802 * read the first occurance, as some spam email has more than one
806 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
808 char nulladdr[] = "<>";
809 already_has_return_path = TRUE;
810 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
812 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
813 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
823 msgblk.headers = (char *)xmalloc(oldlen + 1);
824 (void) memcpy(msgblk.headers, line, linelen);
825 msgblk.headers[oldlen] = '\0';
827 line = msgblk.headers;
834 newlen = oldlen + linelen;
835 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
836 if (newhdrs == NULL) {
840 msgblk.headers = newhdrs;
841 memcpy(msgblk.headers + oldlen, line, linelen);
842 msgblk.headers[newlen] = '\0';
844 line = msgblk.headers + oldlen;
848 /* find offsets of various special headers */
849 if (!strncasecmp("From:", line, 5))
850 from_offs = (line - msgblk.headers);
851 else if (!strncasecmp("Reply-To:", line, 9))
852 reply_to_offs = (line - msgblk.headers);
853 else if (!strncasecmp("Resent-From:", line, 12))
854 resent_from_offs = (line - msgblk.headers);
855 else if (!strncasecmp("Apparently-From:", line, 16))
856 app_from_offs = (line - msgblk.headers);
858 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
860 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
861 * that Sender: *doesn't* have to be a working email address.
863 * The definition of the Sender header in RFC822 says, in
864 * part, "The Sender mailbox specification includes a word
865 * sequence which must correspond to a specific agent (i.e., a
866 * human user or a computer program) rather than a standard
867 * address." That implies that the contents of the Sender
868 * field don't need to be a legal email address at all So
869 * ignore any Sender or Resent-Sender lines unless they
872 * (RFC2822 says the contents of Sender must be a valid mailbox
873 * address, which is also what RFC822 4.4.4 implies.)
875 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
876 sender_offs = (line - msgblk.headers);
877 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
878 resent_sender_offs = (line - msgblk.headers);
881 else if (!strncasecmp("Message-Id:", line, 11))
883 if (ctl->server.uidl)
887 line[IDLEN+12] = 0; /* prevent stack overflow */
888 sscanf(line+12, "%s", id);
889 if (!str_find( &ctl->newsaved, num))
891 struct idlist *newl = save_str(&ctl->newsaved,id,UID_SEEN);
892 newl->val.status.num = num;
896 #endif /* __UNUSED__ */
898 /* if multidrop is on, gather addressee headers */
901 if (!strncasecmp("To:", line, 3)
902 || !strncasecmp("Cc:", line, 3)
903 || !strncasecmp("Bcc:", line, 4)
904 || !strncasecmp("Apparently-To:", line, 14))
906 *to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
907 (*to_chainptr)->offset = (line - msgblk.headers);
908 to_chainptr = &(*to_chainptr)->next;
912 else if (!strncasecmp("Resent-To:", line, 10)
913 || !strncasecmp("Resent-Cc:", line, 10)
914 || !strncasecmp("Resent-Bcc:", line, 11))
916 *resent_to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
917 (*resent_to_chainptr)->offset = (line - msgblk.headers);
918 resent_to_chainptr = &(*resent_to_chainptr)->next;
919 *resent_to_chainptr = NULL;
922 else if (ctl->server.envelope != STRING_DISABLED)
924 if (ctl->server.envelope
925 && strcasecmp(ctl->server.envelope, "Received"))
927 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
929 strlen(ctl->server.envelope)))
931 if (skipcount++ < ctl->server.envskip)
933 env_offs = (line - msgblk.headers);
936 else if (!received_for && !strncasecmp("Received:", line, 9))
938 if (skipcount++ < ctl->server.envskip)
940 received_for = parse_received(ctl, line);
955 * This is the duplicate-message killer code.
957 * When mail delivered to a multidrop mailbox on the server is
958 * addressed to multiple people on the client machine, there will
959 * be one copy left in the box for each recipient. This is not a
960 * problem if we have the actual recipient address to dispatch on
961 * (e.g. because we've mined it out of sendmail trace headers, or
962 * a qmail Delivered-To line, or a declared sender envelope line).
964 * But if we're mining addressees out of the To/Cc/Bcc fields, and
965 * if the mail is addressed to N people, each recipient will
966 * get N copies. This is bad when N > 1.
968 * Foil this by suppressing all but one copy of a message with a
969 * given set of headers.
971 * Note: This implementation only catches runs of successive
972 * messages with the same ID, but that should be good
973 * enough. A more general implementation would have to store
974 * ever-growing lists of seen message-IDs; in a long-running
975 * daemon this would turn into a memory leak even if the
976 * implementation were perfect.
978 * Don't mess with this code casually. It would be way too easy
979 * to break it in a way that blackholed mail. Better to pass
980 * the occasional duplicate than to do that...
983 * The real fix however is to insist on Delivered-To: or similar
984 * headers and require that one copy per recipient be dropped.
985 * Everything else breaks sooner or later.
987 if (MULTIDROP(ctl) && msgblk.headers)
992 MD5Update(&context, (unsigned char *)msgblk.headers, strlen(msgblk.headers));
993 MD5Final(ctl->digest, &context);
995 if (!received_for && env_offs == -1 && !delivered_to)
998 * Hmmm...can MD5 ever yield all zeroes as a hash value?
999 * If so there is a one in 18-quadrillion chance this
1000 * code will incorrectly nuke the first message.
1002 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
1005 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
1009 * Hack time. If the first line of the message was blank, with no headers
1010 * (this happens occasionally due to bad gatewaying software) cons up
1011 * a set of fake headers.
1013 * If you modify the fake header template below, be sure you don't
1014 * make either From or To address @-less, otherwise the reply_hack
1015 * logic will do bad things.
1017 if (msgblk.headers == (char *)NULL)
1019 snprintf(buf, sizeof(buf),
1020 "From: FETCHMAIL-DAEMON\r\n"
1022 "Subject: Headerless mail from %s's mailbox on %s\r\n",
1023 user, fetchmailhost, ctl->remotename, ctl->server.truename);
1024 msgblk.headers = xstrdup(buf);
1028 * We can now process message headers before reading the text.
1029 * In fact we have to, as this will tell us where to forward to.
1032 /* Check for MIME headers indicating possible 8-bit data */
1033 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
1036 if (ctl->server.sdps && sdps_envfrom)
1038 /* We have the real envelope return-path, stored out of band by
1039 * SDPS - that's more accurate than any header is going to be.
1041 strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
1044 #endif /* SDPS_ENABLE */
1046 * If there is a Return-Path address on the message, this was
1047 * almost certainly the MAIL FROM address given the originating
1048 * sendmail. This is the best thing to use for logging the
1049 * message origin (it sets up the right behavior for bounces and
1050 * mailing lists). Otherwise, fall down to the next available
1051 * envelope address (which is the most probable real sender).
1052 * *** The order is important! ***
1053 * This is especially useful when receiving mailing list
1054 * messages in multidrop mode. if a local address doesn't
1055 * exist, the bounce message won't be returned blindly to the
1056 * author or to the list itself but rather to the list manager
1057 * (ex: specified by "Sender:") which is much less annoying. This
1058 * is true for most mailing list packages.
1060 if( !msgblk.return_path[0] ){
1062 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
1063 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
1064 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
1065 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
1066 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
1067 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
1068 /* multi-line MAIL FROM addresses confuse SMTP terribly */
1069 if (ap && !strchr(ap, '\n')) {
1070 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
1071 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1075 /* cons up a list of local recipients */
1076 msgblk.recipients = (struct idlist *)NULL;
1077 accept_count = reject_count = 0;
1078 /* is this a multidrop box? */
1082 if (ctl->server.sdps && sdps_envto)
1084 /* We have the real envelope recipient, stored out of band by
1085 * SDPS - that's more accurate than any header is going to be.
1087 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1090 #endif /* SDPS_ENABLE */
1091 if (env_offs > -1) { /* We have the actual envelope addressee */
1092 if (outlevel >= O_DEBUG) {
1093 const char *tmps = msgblk.headers + env_offs;
1094 size_t l = strcspn(tmps, "\r\n");
1095 report(stdout, GT_("Parsing envelope \"%s\" names \"%-.*s\"\n"), ctl->server.envelope, UCAST_TO_INT(l), tmps);
1097 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1099 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1100 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1102 if (outlevel >= O_DEBUG) {
1103 const char *tmps = delivered_to + 2 + strlen(ctl->server.envelope);
1104 size_t l = strcspn(tmps, "\r\n");
1105 report(stdout, GT_("Parsing envelope \"%s\" names \"%-.*s\"\n"), ctl->server.envelope, UCAST_TO_INT(l), tmps);
1107 find_server_names(delivered_to, ctl, &msgblk.recipients);
1108 xfree(delivered_to);
1109 } else if (received_for) {
1111 * We have the Received for addressee.
1112 * It has to be a mailserver address, or we
1113 * wouldn't have got here.
1114 * We use find_server_names() to let local
1115 * hostnames go through.
1117 if (outlevel >= O_DEBUG) {
1118 const char *tmps = received_for + 2;
1119 size_t l = strcspn(tmps, "\r\n");
1120 report(stdout, GT_("Parsing Received names \"%-.*s\"\n"), UCAST_TO_INT(l), tmps);
1122 find_server_names(received_for, ctl, &msgblk.recipients);
1125 * We haven't extracted the envelope address.
1126 * So check all the "Resent-To" header addresses if
1127 * they exist. If and only if they don't, consider
1128 * the "To" addresses.
1130 register struct addrblk *nextptr;
1131 if (outlevel >= O_DEBUG)
1132 report(stdout, GT_("No envelope recipient found, resorting to header guessing.\n"));
1133 if (resent_to_addrchain) {
1134 /* delete the "To" chain and substitute it
1135 * with the "Resent-To" list
1137 while (to_addrchain) {
1138 nextptr = to_addrchain->next;
1140 to_addrchain = nextptr;
1142 to_addrchain = resent_to_addrchain;
1143 resent_to_addrchain = NULL;
1145 /* now look for remaining adresses */
1146 while (to_addrchain) {
1147 if (outlevel >= O_DEBUG) {
1148 const char *tmps = msgblk.headers+to_addrchain->offset;
1149 size_t l = strcspn(tmps, "\r\n");
1150 report(stdout, GT_("Guessing from header \"%-.*s\".\n"), UCAST_TO_INT(l), tmps);
1153 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1154 nextptr = to_addrchain->next;
1156 to_addrchain = nextptr;
1161 no_local_matches = TRUE;
1162 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1163 if (outlevel >= O_DEBUG)
1165 GT_("no local matches, forwarding to %s\n"),
1169 else /* it's a single-drop box, use first localname */
1170 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1174 * Time to either address the message or decide we can't deliver it yet.
1176 if (ctl->errcount > olderrs) /* there were DNS errors above */
1178 if (outlevel >= O_DEBUG)
1180 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1181 return(PS_TRANSIENT);
1185 /* set up stuffline() so we can deliver the message body through it */
1186 if ((n = open_sink(ctl, &msgblk,
1187 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1195 * Some server/sendmail combinations cause problems when our
1196 * synthetic Received line is before the From header. Cope
1199 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1200 rcv = msgblk.headers;
1201 /* handle ">Received:" lines too */
1202 while (rcv > msgblk.headers && rcv[-1] != '\n')
1204 if (rcv > msgblk.headers)
1209 n = stuffline(ctl, msgblk.headers);
1212 if (!run.invisible && n != -1)
1214 /* utter any per-message Received information we need here */
1215 if (ctl->server.trueaddr) {
1219 e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1220 saddr, sizeof(saddr), NULL, 0,
1223 snprintf(saddr, sizeof(saddr), "(%-.*s)", (int)(sizeof(saddr) - 3), gai_strerror(e));
1224 snprintf(buf, sizeof(buf),
1225 "Received: from %s [%s]\r\n",
1226 ctl->server.truename, saddr);
1228 snprintf(buf, sizeof(buf),
1229 "Received: from %s\r\n", ctl->server.truename);
1231 n = stuffline(ctl, buf);
1235 * We SHOULD (RFC-2821 sec. 4.4/p. 53) make sure to only use
1236 * IANA registered protocol names here.
1238 snprintf(buf, sizeof(buf),
1239 "\tby %s with %s (fetchmail-%s",
1243 if (ctl->server.tracepolls)
1245 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1246 " polling %s account %s",
1247 ctl->server.pollname,
1250 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1254 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1255 n = stuffline(ctl, buf);
1259 if (good_addresses == 0)
1261 snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1262 rcpt_address (ctl, run.postmaster, 0));
1264 else if (good_addresses == 1)
1266 for (idp = msgblk.recipients; idp; idp = idp->next)
1267 if (idp->val.status.mark == XMIT_ACCEPT)
1268 break; /* only report first address */
1270 snprintf(buf+1, sizeof(buf)-1,
1271 "for <%s>", rcpt_address (ctl, idp->id, 1));
1272 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1274 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1279 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1281 n = stuffline(ctl, buf);
1287 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1291 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1296 if (want_progress())
1299 /* write error notifications */
1300 if (no_local_matches || has_nuls || bad_addresses)
1303 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1306 strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1307 if (no_local_matches)
1309 if (reject_count != 1)
1310 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1313 for (idp = msgblk.recipients; idp; idp = idp->next)
1314 if (idp->val.status.mark == XMIT_REJECT)
1316 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1317 GT_("recipient address %s didn't match any local name"), idp->id);
1323 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1324 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1325 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1326 GT_("message has embedded NULs"));
1331 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1332 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1333 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1334 GT_("SMTP listener rejected local recipient addresses: "));
1335 errlen = strlen(errhd);
1336 for (idp = msgblk.recipients; idp; idp = idp->next)
1337 if (idp->val.status.mark == XMIT_RCPTBAD)
1338 errlen += strlen(idp->id) + 2;
1340 errmsg = (char *)xmalloc(errlen + 3);
1341 strcpy(errmsg, errhd);
1342 for (idp = msgblk.recipients; idp; idp = idp->next)
1343 if (idp->val.status.mark == XMIT_RCPTBAD)
1345 strcat(errmsg, idp->id);
1347 strcat(errmsg, ", ");
1352 strcat(errmsg, "\r\n");
1354 /* ship out the error line */
1355 stuffline(ctl, errmsg);
1357 if (errmsg != errhd)
1361 /* issue the delimiter line */
1366 n = stuffline(ctl, buf);
1368 if ((size_t)n == strlen(buf))
1374 int readbody(int sock, struct query *ctl, flag forward, int len)
1375 /* read and dispose of a message body presented on sock */
1376 /* ctl: query control record */
1377 /* sock: to which the server is connected */
1378 /* len: length of message */
1379 /* forward: TRUE to forward */
1382 char buf[MSGBUFSIZE+4];
1384 flag issoftline = FALSE;
1387 * Pass through the text lines in the body.
1389 * Yes, this wants to be ||, not &&. The problem is that in the most
1390 * important delimited protocol, POP3, the length is not reliable.
1391 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1392 * So, for delimited protocols we need to ignore the length here and
1393 * instead drop out of the loop with a break statement when we see
1394 * the message delimiter.
1396 while (protocol->delimited || len > 0)
1398 set_timeout(mytimeout);
1399 /* XXX FIXME: for undelimited protocols that ship the size, such
1400 * as IMAP, we might want to use the count of remaining characters
1401 * instead of the buffer size -- not for fetchmail 6.3.X though */
1402 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1410 /* write the message size dots */
1413 print_ticker(&sizeticker, linelen);
1416 /* Mike Jones, Manchester University, 2006:
1417 * "To fix IMAP MIME Messages in which fetchmail adds the remainder of
1418 * the IMAP packet including the ')' character (part of the IMAP)
1419 * Protocol causing the addition of an extra MIME boundary locally."
1421 * However, we shouldn't do this for delimited protocols:
1422 * many POP3 servers (Microsoft, qmail) goof up message sizes
1423 * so we might end truncating messages prematurely.
1425 if (!protocol->delimited && linelen > len) {
1431 /* check for end of message */
1432 if (protocol->delimited && *inbufp == '.')
1434 if (EMPTYLINE(inbufp+1))
1437 msgblk.msglen--; /* subtract the size of the dot escape */
1440 msgblk.msglen += linelen;
1442 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1443 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1444 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1447 * Soft linebreak, but less than 200 bytes left in
1448 * input buffer. Rather than doing a buffer overrun,
1449 * ignore the soft linebreak, NL-terminate data and
1450 * deliver what we have now.
1451 * (Who writes lines longer than 2K anyway?)
1453 *inbufp = '\n'; *(inbufp+1) = '\0';
1458 /* ship out the text line */
1459 if (forward && (!issoftline))
1464 /* guard against very long lines */
1465 buf[MSGBUFSIZE+1] = '\r';
1466 buf[MSGBUFSIZE+2] = '\n';
1467 buf[MSGBUFSIZE+3] = '\0';
1469 n = stuffline(ctl, buf);
1473 report(stdout, GT_("error writing message text\n"));
1477 else if (want_progress())
1488 void init_transact(const struct method *proto)
1489 /* initialize state for the send and receive functions */
1491 suppress_tags = FALSE;
1493 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1498 static void enshroud(char *buf)
1499 /* shroud a password in the given buffer */
1503 if (shroud[0] && (cp = strstr(buf, shroud)))
1507 sp = cp + strlen(shroud);
1515 #if defined(HAVE_STDARG_H)
1516 void gen_send(int sock, const char *fmt, ... )
1518 void gen_send(sock, fmt, va_alist)
1519 int sock; /* socket to which server is connected */
1520 const char *fmt; /* printf-style format */
1523 /* assemble command in printf(3) style and send to the server */
1525 char buf [MSGBUFSIZE+1];
1528 if (protocol->tagged && !suppress_tags)
1529 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1533 #if defined(HAVE_STDARG_H)
1538 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1541 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1542 SockWrite(sock, buf, strlen(buf));
1544 if (outlevel >= O_MONITOR)
1547 buf[strlen(buf)-2] = '\0';
1548 report(stdout, "%s> %s\n", protocol->name, buf);
1552 /** get one line of input from the server */
1553 int gen_recv(int sock /** socket to which server is connected */,
1554 char *buf /* buffer to receive input */,
1555 int size /* length of buffer */)
1557 int oldphase = phase; /* we don't have to be re-entrant */
1559 phase = SERVER_WAIT;
1560 set_timeout(mytimeout);
1561 if (SockRead(sock, buf, size) == -1)
1565 if(is_idletimeout())
1568 return(PS_IDLETIMEOUT);
1576 if (buf[strlen(buf)-1] == '\n')
1577 buf[strlen(buf)-1] = '\0';
1578 if (buf[strlen(buf)-1] == '\r')
1579 buf[strlen(buf)-1] = '\0';
1580 if (outlevel >= O_MONITOR)
1581 report(stdout, "%s< %s\n", protocol->name, buf);
1587 #if defined(HAVE_STDARG_H)
1588 int gen_transact(int sock, const char *fmt, ... )
1590 int gen_transact(int sock, fmt, va_alist)
1591 int sock; /* socket to which server is connected */
1592 const char *fmt; /* printf-style format */
1595 /* assemble command in printf(3) style, send to server, accept a response */
1598 char buf [MSGBUFSIZE+1];
1600 int oldphase = phase; /* we don't have to be re-entrant */
1602 phase = SERVER_WAIT;
1604 if (protocol->tagged && !suppress_tags)
1605 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1609 #if defined(HAVE_STDARG_H)
1614 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1617 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1618 ok = SockWrite(sock, buf, strlen(buf));
1619 if (ok == -1 || (size_t)ok != strlen(buf)) {
1620 /* short write, bail out */
1624 if (outlevel >= O_MONITOR)
1627 buf[strlen(buf)-2] = '\0';
1628 report(stdout, "%s> %s\n", protocol->name, buf);
1631 /* we presume this does its own response echoing */
1632 ok = (protocol->parse_response)(sock, buf);
1638 /* transact.c ends here */