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)
27 #ifdef HAVE_NET_SOCKET_H
28 #include <net/socket.h>
30 #include <sys/socket.h>
36 #include "fetchmail.h"
38 /* global variables: please reinitialize them explicitly for proper
39 * working in daemon mode */
41 /* session variables initialized in init_transact() */
42 int suppress_tags = FALSE; /* emit tags? */
45 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
46 static struct method *protocol;
47 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
49 /* session variables initialized in do_session() */
50 int mytimeout; /* value of nonreponse timeout */
52 /* mail variables initialized in readheaders() */
54 static int accept_count, reject_count;
56 /** add given address to xmit_names if it exactly matches a full address
57 * \returns nonzero if matched */
58 static int map_address(const char *addr, struct query *ctl, struct idlist **xmit_names)
62 lname = idpair_find(&ctl->localnames, addr);
64 if (outlevel >= O_DEBUG)
65 report(stdout, GT_("mapped address %s to local %s\n"), addr, lname);
66 save_str(xmit_names, lname, XMIT_ACCEPT);
72 /** add given name to xmit_names if it matches declared localnames */
73 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
74 /* name: name to map */
75 /* ctl: list of permissible aliases */
76 /* xmit_names: list of recipient names parsed out */
80 lname = idpair_find(&ctl->localnames, name);
81 if (!lname && ctl->wildcard)
84 if (lname != (char *)NULL)
86 if (outlevel >= O_DEBUG)
87 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
88 save_str(xmit_names, lname, XMIT_ACCEPT);
93 static void find_server_names(const char *hdr,
95 struct idlist **xmit_names)
96 /* parse names out of a RFC822 header into an ID list */
97 /* hdr: RFC822 header in question */
98 /* ctl: list of permissible aliases */
99 /* xmit_names: list of recipient names parsed out */
101 if (hdr == (char *)NULL)
107 for (cp = nxtaddr(hdr); cp != NULL; cp = nxtaddr(NULL))
112 * Handle empty address from a To: header containing only
119 * If the name of the user begins with a qmail virtual
120 * domain prefix, ignore the prefix. Doing this here
121 * means qvirtual will work either with ordinary name
122 * mapping or with a localdomains option.
124 if (ctl->server.qvirtual)
126 int sl = strlen(ctl->server.qvirtual);
128 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
132 if ((atsign = strchr((char *)cp, '@'))) {
135 /* try to match full address first, this takes
136 * precedence over localdomains and alias mappings */
137 if (map_address(cp, ctl, xmit_names))
141 * Does a trailing segment of the hostname match something
142 * on the localdomains list? If so, save the whole name
145 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
148 rhs = atsign + (strlen(atsign) - strlen(idp->id));
150 (rhs[-1] == '.' || rhs[-1] == '@') &&
151 strcasecmp(rhs, idp->id) == 0)
153 if (outlevel >= O_DEBUG)
154 report(stdout, GT_("passed through %s matching %s\n"),
156 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
162 /* if we matched a local domain, idp != NULL */
166 * Check to see if the right-hand part is an alias
167 * or MX equivalent of the mailserver. If it's
168 * not, skip this name. If it is, we'll keep
169 * going and try to find a mapping to a client name.
171 if (!is_host_alias(atsign+1, ctl, &ai0))
173 save_str(xmit_names, cp, XMIT_REJECT);
179 map_name(cp, ctl, xmit_names);
187 * Return zero on a syntactically invalid address, nz on a valid one.
189 * This used to be strchr(a, '.'), but it turns out that lines like this
191 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
192 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
194 * are not uncommon. So now we just check that the following token is
195 * not itself an email address.
197 #define VALID_ADDRESS(a) !strchr(a, '@')
199 static char *parse_received(struct query *ctl, char *bufp)
200 /* try to extract real address from the Received line */
201 /* If a valid Received: line is found, we return the full address in
202 * a buffer which can be parsed from nxtaddr(). This is to ansure that
203 * the local domain part of the address can be passed along in
204 * find_server_names() if it contains one.
205 * Note: We should return a dummy header containing the address
206 * which makes nxtaddr() behave correctly.
209 char *base, *ok = (char *)NULL;
210 static char rbuf[HOSTLEN + USERNAMELEN + 4];
211 struct addrinfo *ai0;
213 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
216 * Try to extract the real envelope addressee. We look here
217 * specifically for the mailserver's Received line.
218 * Note: this will only work for sendmail, or an MTA that
219 * shares sendmail's convention for embedding the envelope
220 * address in the Received line. Sendmail itself only
221 * does this when the mail has a single recipient.
223 if (outlevel >= O_DEBUG)
224 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
226 /* search for whitepace-surrounded "by" followed by valid address */
227 for (base = bufp; ; base = ok + 2)
229 if (!(ok = strstr(base, "by")))
231 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
237 /* extract space-delimited token after "by" */
238 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
241 for (; *sp && !isspace((unsigned char)*sp); sp++)
245 /* look for valid address */
246 if (VALID_ADDRESS(rbuf))
249 ok = sp - 1; /* arrange to skip this token */
255 * If it's a DNS name of the mail server, look for the
256 * recipient name after a following "for". Otherwise
259 if (is_host_alias(rbuf, ctl, &ai0))
261 if (outlevel >= O_DEBUG)
263 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
267 if (outlevel >= O_DEBUG)
269 GT_("line rejected, %s is not an alias of the mailserver\n"),
274 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
275 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
277 if (!(ok = strstr(base, "for")))
279 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
285 /* extract space-delimited token after "for" */
286 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
289 for (; !isspace((unsigned char)*sp); sp++)
293 if (strchr(rbuf, '@'))
296 ok = sp - 1; /* arrange to skip this token */
301 flag want_gt = FALSE;
304 /* char after "for" could be space or a continuation newline */
305 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
308 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
309 RBUF_WRITE(' '); /* with nxtaddr()... */
315 while (*sp == '@') /* skip routes */
316 while (*sp && *sp++ != ':')
319 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
321 if (!isspace((unsigned char)*sp))
328 /* uh oh -- whitespace here can't be right! */
334 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
342 if (outlevel >= O_DEBUG)
343 report(stdout, GT_("no Received address found\n"));
348 if (outlevel >= O_DEBUG) {
349 char *lf = rbuf + strlen(rbuf)-1;
351 if (outlevel >= O_DEBUG)
352 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
359 /* shared by readheaders and readbody */
360 static int sizeticker;
362 /** Print ticker based on a amount of data transferred of \a bytes.
363 * Increments \a *tickervar by \a bytes, and if it exceeds
364 * \a SIZETICKER, print a dot and reduce *tickervar by \a SIZETICKER. */
365 static void print_ticker(int *tickervar, int bytes)
368 while (*tickervar >= SIZETICKER)
375 *tickervar -= SIZETICKER;
379 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
380 || ((s)[0] == '\n' && (s)[1] == '\0'))
382 static int end_of_header (const char *s)
383 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
387 return (s[0] == '\n' && s[1] == '\0');
390 int readheaders(int sock,
395 flag *suppress_readbody)
396 /* read message headers and ship to SMTP or MDA */
397 /* sock: to which the server is connected */
398 /* fetchlen: length of message according to fetch response */
399 /* reallen: length of message according to getsizes */
400 /* ctl: query control record */
401 /* num: index of message */
402 /* suppress_readbody: whether call to readbody() should be supressed */
407 struct addrblk *next;
409 struct addrblk *to_addrchain = NULL;
410 struct addrblk **to_chainptr = &to_addrchain;
411 struct addrblk *resent_to_addrchain = NULL;
412 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
414 char buf[MSGBUFSIZE+1];
415 int from_offs, reply_to_offs, resent_from_offs;
416 int app_from_offs, sender_offs, resent_sender_offs;
418 char *received_for, *rcv, *cp;
419 static char *delivered_to = NULL;
420 int n, oldlen, ch, remaining, skipcount;
422 int delivered_to_count;
424 flag no_local_matches = FALSE;
426 int olderrs, good_addresses, bad_addresses;
427 int retain_mail = 0, refuse_mail = 0;
428 flag already_has_return_path = FALSE;
432 msgblk.return_path[0] = '\0';
433 olderrs = ctl->errcount;
435 /* read message headers */
436 msgblk.reallen = reallen;
439 * We used to free the header block unconditionally at the end of
440 * readheaders, but it turns out that if close_sink() hits an error
441 * condition the code for sending bouncemail will actually look
442 * at the freed storage and coredump...
444 xfree(msgblk.headers);
445 free_str_list(&msgblk.recipients);
448 /* initially, no message digest */
449 memset(ctl->digest, '\0', sizeof(ctl->digest));
452 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
453 sender_offs = resent_sender_offs = env_offs = -1;
457 delivered_to_count = 0;
460 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
464 line = (char *)xmalloc(sizeof(buf));
471 set_timeout(mytimeout);
472 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
480 * Smash out any NULs, they could wreak havoc later on.
481 * Some network stacks seem to generate these at random,
482 * especially (according to reports) at the beginning of the
483 * first read. NULs are illegal in RFC822 format.
485 for (sp = tp = buf; sp < buf + n; sp++)
498 * Try to gracefully handle the case where the length of a
499 * line exceeds MSGBUFSIZE.
501 if (n && buf[n-1] != '\n')
503 rline = (char *) realloc(line, linelen + 1);
510 memcpy(line + linelen - n, buf, n);
511 line[linelen] = '\0';
512 ch = ' '; /* So the next iteration starts */
516 /* lines may not be properly CRLF terminated; fix this for qmail */
517 /* we don't want to overflow the buffer here */
518 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
521 rline = (char *) realloc(line, linelen + 2);
528 memcpy(line + linelen - n, buf, n - 1);
529 tcp = line + linelen - 1;
538 rline = (char *) realloc(line, linelen + 1);
545 memcpy(line + linelen - n, buf, n + 1);
548 /* check for end of headers */
549 if (end_of_header(line))
552 if (linelen != strlen (line))
555 goto process_headers;
559 * Check for end of message immediately. If one of your folders
560 * has been mangled, the delimiter may occur directly after the
563 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
565 if (suppress_readbody)
566 *suppress_readbody = TRUE;
567 goto eoh; /* above */
571 * At least one brain-dead website (netmind.com) is known to
572 * send out robotmail that's missing the RFC822 delimiter blank
573 * line before the body! Without this check fetchmail segfaults.
574 * With it, we treat such messages as spam and refuse them.
576 * Frederic Marchal reported in February 2006 that hotmail
577 * or something improperly wrapped a very long TO header
578 * (wrapped without inserting whitespace in the continuation
579 * line) and found that this code thus refused a message
580 * that should have been delivered.
582 * XXX FIXME: we should probably wrap the message up as
583 * message/rfc822 attachment and forward to postmaster (Rob
586 if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
588 if (linelen != strlen (line))
590 if (outlevel > O_SILENT)
592 GT_("incorrect header line found while scanning headers\n"));
593 if (outlevel >= O_VERBOSE)
594 report (stdout, GT_("line: %s"), line);
598 /* check for RFC822 continuations */
599 set_timeout(mytimeout);
603 (ch == ' ' || ch == '\t'); /* continuation to next line? */
605 /* write the message size dots */
606 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
608 print_ticker(&sizeticker, linelen);
612 * Decode MIME encoded headers. We MUST do this before
613 * looking at the Content-Type / Content-Transfer-Encoding
614 * headers (RFC 2046).
616 if ( ctl->mimedecode )
620 /* the line is now shorter. So we retrace back till we find
621 * our terminating combination \n\0, we move backwards to
622 * make sure that we don't catch some \n\0 stored in the
623 * decoded part of the message */
624 for (tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
625 if (tcp > line) linelen = tcp - line;
629 /* skip processing if we are going to retain or refuse this mail */
630 if (retain_mail || refuse_mail)
636 /* we see an ordinary (non-header, non-message-delimiter) line */
637 if (linelen != strlen (line))
641 * The University of Washington IMAP server (the reference
642 * implementation of IMAP4 written by Mark Crispin) relies
643 * on being able to keep base-UID information in a special
644 * message at the head of the mailbox. This message should
645 * neither be deleted nor forwarded.
647 * An example for such a message is (keep this in so people
648 * find it when looking where the special code is to handle the
651 * From MAILER-DAEMON Wed Nov 23 11:38:42 2005
652 * Date: 23 Nov 2005 11:38:42 +0100
653 * From: Mail System Internal Data <MAILER-DAEMON@mail.example.org>
654 * Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
655 * Message-ID: <1132742322@mail.example.org>
656 * X-IMAP: 1132742306 0000000001
659 * This text is part of the internal format of your mail folder, and is not
660 * a real message. It is created automatically by the mail system software.
661 * If deleted, important folder data will be lost, and it will be re-created
662 * with the data reset to initial values.
664 * This message is only visible if a POP3 server that is unaware
665 * of these UWIMAP messages is used besides UWIMAP or PINE.
667 * We will just check if the first message in the mailbox has an
672 * We disable this check under POP2 because there's no way to
673 * prevent deletion of the message. So at least we ought to
674 * forward it to the user so he or she will have some clue
675 * that things have gone awry.
677 if (servport("pop2") != servport(protocol->service))
678 #endif /* POP2_ENABLE */
679 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
686 * This code prevents fetchmail from becoming an accessory after
687 * the fact to upstream sendmails with the `E' option on. It also
688 * copes with certain brain-dead POP servers (like NT's) that pass
689 * through Unix from_ lines.
691 * Either of these bugs can result in a non-RFC822 line at the
692 * beginning of the headers. If fetchmail just passes it
693 * through, the client listener may think the message has *no*
694 * headers (since the first) line it sees doesn't look
695 * RFC822-conformant) and fake up a set.
697 * What the user would see in this case is bogus (synthesized)
698 * headers, followed by a blank line, followed by the >From,
699 * followed by the real headers, followed by a blank line,
702 * We forestall this lossage by tossing anything that looks
703 * like an escaped or passed-through From_ line in headers.
704 * These aren't RFC822 so our conscience is clear...
706 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
713 * We remove all Delivered-To: headers if dropdelivered is set
714 * - special care must be taken if Delivered-To: is also used
715 * as envelope at the same time.
717 * This is to avoid false mail loops errors when delivering
718 * local messages to and from a Postfix or qmail mailserver.
720 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
723 ctl->server.envelope == STRING_DISABLED ||
724 !ctl->server.envelope ||
725 strcasecmp(ctl->server.envelope, "Delivered-To") ||
726 delivered_to_count != ctl->server.envskip)
730 delivered_to_count++;
735 * If we see a Status line, it may have been inserted by an MUA
736 * on the mail host, or it may have been inserted by the server
737 * program after the headers in the transaction stream. This
738 * can actually hose some new-mail notifiers such as xbuffy,
739 * which assumes any Status line came from a *local* MDA and
740 * therefore indicates that the message has been seen.
742 * Some buggy POP servers (including at least the 3.3(20)
743 * version of the one distributed with IMAP) insert empty
744 * Status lines in the transaction stream; we'll chuck those
745 * unconditionally. Nonempty ones get chucked if the user
746 * turns on the dropstatus flag.
751 if (!strncasecmp(line, "Status:", 7))
753 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
758 while (*cp && isspace((unsigned char)*cp)) cp++;
759 if (!*cp || ctl->dropstatus)
768 line = reply_hack(line, ctl->server.truename, &linelen);
771 * OK, this is messy. If we're forwarding by SMTP, it's the
772 * SMTP-receiver's job (according to RFC821, page 22, section
773 * 4.1.1) to generate a Return-Path line on final delivery.
774 * The trouble is, we've already got one because the
775 * mailserver's SMTP thought *it* was responsible for final
778 * Stash away the contents of Return-Path (as modified by reply_hack)
779 * for use in generating MAIL FROM later on, then prevent the header
780 * from being saved with the others. In effect, we strip it off here.
782 * If the SMTP server conforms to the standards, and fetchmail gets the
783 * envelope sender from the Return-Path, the new Return-Path should be
784 * exactly the same as the original one.
786 * We do *not* want to ignore empty Return-Path headers. These should
787 * be passed through as a way of indicating that a message should
788 * not trigger bounces if delivery fails. What we *do* need to do is
789 * make sure we never try to rewrite such a blank Return-Path. We
790 * handle this with a check for <> in the rewrite logic above.
792 * Also, if an email has multiple Return-Path: headers, we only
793 * read the first occurance, as some spam email has more than one
797 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
799 already_has_return_path = TRUE;
800 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
802 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
803 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
813 msgblk.headers = (char *)xmalloc(oldlen + 1);
814 (void) memcpy(msgblk.headers, line, linelen);
815 msgblk.headers[oldlen] = '\0';
817 line = msgblk.headers;
824 newlen = oldlen + linelen;
825 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
826 if (newhdrs == NULL) {
830 msgblk.headers = newhdrs;
831 memcpy(msgblk.headers + oldlen, line, linelen);
832 msgblk.headers[newlen] = '\0';
834 line = msgblk.headers + oldlen;
838 /* find offsets of various special headers */
839 if (!strncasecmp("From:", line, 5))
840 from_offs = (line - msgblk.headers);
841 else if (!strncasecmp("Reply-To:", line, 9))
842 reply_to_offs = (line - msgblk.headers);
843 else if (!strncasecmp("Resent-From:", line, 12))
844 resent_from_offs = (line - msgblk.headers);
845 else if (!strncasecmp("Apparently-From:", line, 16))
846 app_from_offs = (line - msgblk.headers);
848 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
850 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
851 * that Sender: *doesn't* have to be a working email address.
853 * The definition of the Sender header in RFC822 says, in
854 * part, "The Sender mailbox specification includes a word
855 * sequence which must correspond to a specific agent (i.e., a
856 * human user or a computer program) rather than a standard
857 * address." That implies that the contents of the Sender
858 * field don't need to be a legal email address at all So
859 * ignore any Sender or Resent-Sender lines unless they
862 * (RFC2822 says the contents of Sender must be a valid mailbox
863 * address, which is also what RFC822 4.4.4 implies.)
865 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
866 sender_offs = (line - msgblk.headers);
867 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
868 resent_sender_offs = (line - msgblk.headers);
871 else if (!strncasecmp("Message-Id:", line, 11))
873 if (ctl->server.uidl)
877 line[IDLEN+12] = 0; /* prevent stack overflow */
878 sscanf(line+12, "%s", id);
879 if (!str_find( &ctl->newsaved, num))
881 struct idlist *newl = save_str(&ctl->newsaved,id,UID_SEEN);
882 newl->val.status.num = num;
886 #endif /* __UNUSED__ */
888 /* if multidrop is on, gather addressee headers */
891 if (!strncasecmp("To:", line, 3)
892 || !strncasecmp("Cc:", line, 3)
893 || !strncasecmp("Bcc:", line, 4)
894 || !strncasecmp("Apparently-To:", line, 14))
896 *to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
897 (*to_chainptr)->offset = (line - msgblk.headers);
898 to_chainptr = &(*to_chainptr)->next;
902 else if (!strncasecmp("Resent-To:", line, 10)
903 || !strncasecmp("Resent-Cc:", line, 10)
904 || !strncasecmp("Resent-Bcc:", line, 11))
906 *resent_to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
907 (*resent_to_chainptr)->offset = (line - msgblk.headers);
908 resent_to_chainptr = &(*resent_to_chainptr)->next;
909 *resent_to_chainptr = NULL;
912 else if (ctl->server.envelope != STRING_DISABLED)
914 if (ctl->server.envelope
915 && strcasecmp(ctl->server.envelope, "Received"))
917 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
919 strlen(ctl->server.envelope)))
921 if (skipcount++ < ctl->server.envskip)
923 env_offs = (line - msgblk.headers);
926 else if (!received_for && !strncasecmp("Received:", line, 9))
928 if (skipcount++ < ctl->server.envskip)
930 received_for = parse_received(ctl, line);
945 * This is the duplicate-message killer code.
947 * When mail delivered to a multidrop mailbox on the server is
948 * addressed to multiple people on the client machine, there will
949 * be one copy left in the box for each recipient. This is not a
950 * problem if we have the actual recipient address to dispatch on
951 * (e.g. because we've mined it out of sendmail trace headers, or
952 * a qmail Delivered-To line, or a declared sender envelope line).
954 * But if we're mining addressees out of the To/Cc/Bcc fields, and
955 * if the mail is addressed to N people, each recipient will
956 * get N copies. This is bad when N > 1.
958 * Foil this by suppressing all but one copy of a message with a
959 * given set of headers.
961 * Note: This implementation only catches runs of successive
962 * messages with the same ID, but that should be good
963 * enough. A more general implementation would have to store
964 * ever-growing lists of seen message-IDs; in a long-running
965 * daemon this would turn into a memory leak even if the
966 * implementation were perfect.
968 * Don't mess with this code casually. It would be way too easy
969 * to break it in a way that blackholed mail. Better to pass
970 * the occasional duplicate than to do that...
973 * The real fix however is to insist on Delivered-To: or similar
974 * headers and require that one copy per recipient be dropped.
975 * Everything else breaks sooner or later.
977 if (MULTIDROP(ctl) && msgblk.headers)
982 MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
983 MD5Final(ctl->digest, &context);
985 if (!received_for && env_offs == -1 && !delivered_to)
988 * Hmmm...can MD5 ever yield all zeroes as a hash value?
989 * If so there is a one in 18-quadrillion chance this
990 * code will incorrectly nuke the first message.
992 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
995 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
999 * Hack time. If the first line of the message was blank, with no headers
1000 * (this happens occasionally due to bad gatewaying software) cons up
1001 * a set of fake headers.
1003 * If you modify the fake header template below, be sure you don't
1004 * make either From or To address @-less, otherwise the reply_hack
1005 * logic will do bad things.
1007 if (msgblk.headers == (char *)NULL)
1009 snprintf(buf, sizeof(buf),
1010 "From: FETCHMAIL-DAEMON\r\n"
1012 "Subject: Headerless mail from %s's mailbox on %s\r\n",
1013 user, fetchmailhost, ctl->remotename, ctl->server.truename);
1014 msgblk.headers = xstrdup(buf);
1018 * We can now process message headers before reading the text.
1019 * In fact we have to, as this will tell us where to forward to.
1022 /* Check for MIME headers indicating possible 8-bit data */
1023 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
1026 if (ctl->server.sdps && sdps_envfrom)
1028 /* We have the real envelope return-path, stored out of band by
1029 * SDPS - that's more accurate than any header is going to be.
1031 strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
1034 #endif /* SDPS_ENABLE */
1036 * If there is a Return-Path address on the message, this was
1037 * almost certainly the MAIL FROM address given the originating
1038 * sendmail. This is the best thing to use for logging the
1039 * message origin (it sets up the right behavior for bounces and
1040 * mailing lists). Otherwise, fall down to the next available
1041 * envelope address (which is the most probable real sender).
1042 * *** The order is important! ***
1043 * This is especially useful when receiving mailing list
1044 * messages in multidrop mode. if a local address doesn't
1045 * exist, the bounce message won't be returned blindly to the
1046 * author or to the list itself but rather to the list manager
1047 * (ex: specified by "Sender:") which is much less annoying. This
1048 * is true for most mailing list packages.
1050 if( !msgblk.return_path[0] ){
1052 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
1053 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
1054 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
1055 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
1056 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
1057 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
1058 /* multi-line MAIL FROM addresses confuse SMTP terribly */
1059 if (ap && !strchr(ap, '\n')) {
1060 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
1061 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1065 /* cons up a list of local recipients */
1066 msgblk.recipients = (struct idlist *)NULL;
1067 accept_count = reject_count = 0;
1068 /* is this a multidrop box? */
1072 if (ctl->server.sdps && sdps_envto)
1074 /* We have the real envelope recipient, stored out of band by
1075 * SDPS - that's more accurate than any header is going to be.
1077 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1080 #endif /* SDPS_ENABLE */
1081 if (env_offs > -1) /* We have the actual envelope addressee */
1082 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1083 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1084 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1086 find_server_names(delivered_to, ctl, &msgblk.recipients);
1087 xfree(delivered_to);
1089 else if (received_for)
1091 * We have the Received for addressee.
1092 * It has to be a mailserver address, or we
1093 * wouldn't have got here.
1094 * We use find_server_names() to let local
1095 * hostnames go through.
1097 find_server_names(received_for, ctl, &msgblk.recipients);
1101 * We haven't extracted the envelope address.
1102 * So check all the "Resent-To" header addresses if
1103 * they exist. If and only if they don't, consider
1104 * the "To" addresses.
1106 register struct addrblk *nextptr;
1107 if (resent_to_addrchain) {
1108 /* delete the "To" chain and substitute it
1109 * with the "Resent-To" list
1111 while (to_addrchain) {
1112 nextptr = to_addrchain->next;
1114 to_addrchain = nextptr;
1116 to_addrchain = resent_to_addrchain;
1117 resent_to_addrchain = NULL;
1119 /* now look for remaining adresses */
1120 while (to_addrchain) {
1121 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1122 nextptr = to_addrchain->next;
1124 to_addrchain = nextptr;
1129 no_local_matches = TRUE;
1130 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1131 if (outlevel >= O_DEBUG)
1133 GT_("no local matches, forwarding to %s\n"),
1137 else /* it's a single-drop box, use first localname */
1138 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1142 * Time to either address the message or decide we can't deliver it yet.
1144 if (ctl->errcount > olderrs) /* there were DNS errors above */
1146 if (outlevel >= O_DEBUG)
1148 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1149 return(PS_TRANSIENT);
1153 /* set up stuffline() so we can deliver the message body through it */
1154 if ((n = open_sink(ctl, &msgblk,
1155 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1163 * Some server/sendmail combinations cause problems when our
1164 * synthetic Received line is before the From header. Cope
1167 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1168 rcv = msgblk.headers;
1169 /* handle ">Received:" lines too */
1170 while (rcv > msgblk.headers && rcv[-1] != '\n')
1172 if (rcv > msgblk.headers)
1177 n = stuffline(ctl, msgblk.headers);
1180 if (!run.invisible && n != -1)
1182 /* utter any per-message Received information we need here */
1183 if (ctl->server.trueaddr) {
1187 e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1188 saddr, sizeof(saddr), NULL, 0,
1191 snprintf(saddr, sizeof(saddr), "(%-.*s)", (int)(sizeof(saddr) - 3), gai_strerror(e));
1192 snprintf(buf, sizeof(buf),
1193 "Received: from %s [%s]\r\n",
1194 ctl->server.truename, saddr);
1196 snprintf(buf, sizeof(buf),
1197 "Received: from %s\r\n", ctl->server.truename);
1199 n = stuffline(ctl, buf);
1203 * We SHOULD (RFC-2821 sec. 4.4/p. 53) make sure to only use
1204 * IANA registered protocol names here.
1206 snprintf(buf, sizeof(buf),
1207 "\tby %s with %s (fetchmail-%s",
1211 if (ctl->server.tracepolls)
1213 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1214 " polling %s account %s",
1215 ctl->server.pollname,
1218 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1222 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1223 n = stuffline(ctl, buf);
1227 if (good_addresses == 0)
1229 snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1230 rcpt_address (ctl, run.postmaster, 0));
1232 else if (good_addresses == 1)
1234 for (idp = msgblk.recipients; idp; idp = idp->next)
1235 if (idp->val.status.mark == XMIT_ACCEPT)
1236 break; /* only report first address */
1237 snprintf(buf+1, sizeof(buf)-1,
1238 "for <%s>", rcpt_address (ctl, idp->id, 1));
1239 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1241 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1246 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1248 n = stuffline(ctl, buf);
1254 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1258 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1263 if (want_progress())
1266 /* write error notifications */
1267 if (no_local_matches || has_nuls || bad_addresses)
1270 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1273 strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1274 if (no_local_matches)
1276 if (reject_count != 1)
1277 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1280 for (idp = msgblk.recipients; idp; idp = idp->next)
1281 if (idp->val.status.mark == XMIT_REJECT)
1283 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1284 GT_("recipient address %s didn't match any local name"), idp->id);
1290 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1291 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1292 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1293 GT_("message has embedded NULs"));
1298 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1299 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1300 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1301 GT_("SMTP listener rejected local recipient addresses: "));
1302 errlen = strlen(errhd);
1303 for (idp = msgblk.recipients; idp; idp = idp->next)
1304 if (idp->val.status.mark == XMIT_RCPTBAD)
1305 errlen += strlen(idp->id) + 2;
1307 errmsg = (char *)xmalloc(errlen + 3);
1308 strcpy(errmsg, errhd);
1309 for (idp = msgblk.recipients; idp; idp = idp->next)
1310 if (idp->val.status.mark == XMIT_RCPTBAD)
1312 strcat(errmsg, idp->id);
1314 strcat(errmsg, ", ");
1319 strcat(errmsg, "\r\n");
1321 /* ship out the error line */
1322 stuffline(ctl, errmsg);
1324 if (errmsg != errhd)
1328 /* issue the delimiter line */
1333 n = stuffline(ctl, buf);
1335 if ((size_t)n == strlen(buf))
1341 int readbody(int sock, struct query *ctl, flag forward, int len)
1342 /* read and dispose of a message body presented on sock */
1343 /* ctl: query control record */
1344 /* sock: to which the server is connected */
1345 /* len: length of message */
1346 /* forward: TRUE to forward */
1349 char buf[MSGBUFSIZE+4];
1351 flag issoftline = FALSE;
1354 * Pass through the text lines in the body.
1356 * Yes, this wants to be ||, not &&. The problem is that in the most
1357 * important delimited protocol, POP3, the length is not reliable.
1358 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1359 * So, for delimited protocols we need to ignore the length here and
1360 * instead drop out of the loop with a break statement when we see
1361 * the message delimiter.
1363 while (protocol->delimited || len > 0)
1365 set_timeout(mytimeout);
1366 /* XXX FIXME: for undelimited protocols that ship the size, such
1367 * as IMAP, we might want to use the count of remaining characters
1368 * instead of the buffer size -- not for fetchmail 6.3.X though */
1369 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1377 /* write the message size dots */
1380 print_ticker(&sizeticker, linelen);
1383 /* Mike Jones, Manchester University, 2006:
1384 * "To fix IMAP MIME Messages in which fetchmail adds the remainder of
1385 * the IMAP packet including the ')' character (part of the IMAP)
1386 * Protocol causing the addition of an extra MIME boundary locally."
1388 * However, we shouldn't do this for delimited protocols:
1389 * many POP3 servers (Microsoft, qmail) goof up message sizes
1390 * so we might end truncating messages prematurely.
1392 if (!protocol->delimited && linelen > len) {
1398 /* check for end of message */
1399 if (protocol->delimited && *inbufp == '.')
1401 if (EMPTYLINE(inbufp+1))
1404 msgblk.msglen--; /* subtract the size of the dot escape */
1407 msgblk.msglen += linelen;
1409 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1410 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1411 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1414 * Soft linebreak, but less than 200 bytes left in
1415 * input buffer. Rather than doing a buffer overrun,
1416 * ignore the soft linebreak, NL-terminate data and
1417 * deliver what we have now.
1418 * (Who writes lines longer than 2K anyway?)
1420 *inbufp = '\n'; *(inbufp+1) = '\0';
1425 /* ship out the text line */
1426 if (forward && (!issoftline))
1431 /* guard against very long lines */
1432 buf[MSGBUFSIZE+1] = '\r';
1433 buf[MSGBUFSIZE+2] = '\n';
1434 buf[MSGBUFSIZE+3] = '\0';
1436 n = stuffline(ctl, buf);
1440 report(stdout, GT_("error writing message text\n"));
1444 else if (want_progress())
1455 void init_transact(const struct method *proto)
1456 /* initialize state for the send and receive functions */
1458 suppress_tags = FALSE;
1460 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1461 protocol = (struct method *)proto;
1465 static void enshroud(char *buf)
1466 /* shroud a password in the given buffer */
1470 if (shroud[0] && (cp = strstr(buf, shroud)))
1474 sp = cp + strlen(shroud);
1482 #if defined(HAVE_STDARG_H)
1483 void gen_send(int sock, const char *fmt, ... )
1485 void gen_send(sock, fmt, va_alist)
1486 int sock; /* socket to which server is connected */
1487 const char *fmt; /* printf-style format */
1490 /* assemble command in printf(3) style and send to the server */
1492 char buf [MSGBUFSIZE+1];
1495 if (protocol->tagged && !suppress_tags)
1496 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1500 #if defined(HAVE_STDARG_H)
1505 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1508 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1509 SockWrite(sock, buf, strlen(buf));
1511 if (outlevel >= O_MONITOR)
1514 buf[strlen(buf)-2] = '\0';
1515 report(stdout, "%s> %s\n", protocol->name, buf);
1519 /** get one line of input from the server */
1520 int gen_recv(int sock /** socket to which server is connected */,
1521 char *buf /* buffer to receive input */,
1522 int size /* length of buffer */)
1524 int oldphase = phase; /* we don't have to be re-entrant */
1526 phase = SERVER_WAIT;
1527 set_timeout(mytimeout);
1528 if (SockRead(sock, buf, size) == -1)
1532 if(is_idletimeout())
1535 return(PS_IDLETIMEOUT);
1543 if (buf[strlen(buf)-1] == '\n')
1544 buf[strlen(buf)-1] = '\0';
1545 if (buf[strlen(buf)-1] == '\r')
1546 buf[strlen(buf)-1] = '\0';
1547 if (outlevel >= O_MONITOR)
1548 report(stdout, "%s< %s\n", protocol->name, buf);
1554 #if defined(HAVE_STDARG_H)
1555 int gen_transact(int sock, const char *fmt, ... )
1557 int gen_transact(int sock, fmt, va_alist)
1558 int sock; /* socket to which server is connected */
1559 const char *fmt; /* printf-style format */
1562 /* assemble command in printf(3) style, send to server, accept a response */
1565 char buf [MSGBUFSIZE+1];
1567 int oldphase = phase; /* we don't have to be re-entrant */
1569 phase = SERVER_WAIT;
1571 if (protocol->tagged && !suppress_tags)
1572 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1576 #if defined(HAVE_STDARG_H)
1581 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1584 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1585 ok = SockWrite(sock, buf, strlen(buf));
1586 if (ok == -1 || (size_t)ok != strlen(buf)) {
1587 /* short write, bail out */
1591 if (outlevel >= O_MONITOR)
1594 buf[strlen(buf)-2] = '\0';
1595 report(stdout, "%s> %s\n", protocol->name, buf);
1598 /* we presume this does its own response echoing */
1599 ok = (protocol->parse_response)(sock, buf);
1605 /* transact.c ends here */