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.
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>
32 #include <sys/socket.h>
38 #include "fetchmail.h"
40 /* global variables: please reinitialize them explicitly for proper
41 * working in daemon mode */
43 /* session variables initialized in init_transact() */
44 int suppress_tags = FALSE; /* emit tags? */
47 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
48 static struct method *protocol;
49 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
51 /* session variables initialized in do_session() */
52 int mytimeout; /* value of nonreponse timeout */
54 /* mail variables initialized in readheaders() */
56 static int accept_count, reject_count;
58 /** add given address to xmit_names if it exactly matches a full address
59 * \returns nonzero if matched */
60 static int map_address(const char *addr, struct query *ctl, struct idlist **xmit_names)
64 lname = idpair_find(&ctl->localnames, addr);
66 if (outlevel >= O_DEBUG)
67 report(stdout, GT_("mapped address %s to local %s\n"), addr, lname);
68 save_str(xmit_names, lname, XMIT_ACCEPT);
74 /** add given name to xmit_names if it matches declared localnames */
75 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
76 /* name: name to map */
77 /* ctl: list of permissible aliases */
78 /* xmit_names: list of recipient names parsed out */
82 lname = idpair_find(&ctl->localnames, name);
83 if (!lname && ctl->wildcard)
86 if (lname != (char *)NULL)
88 if (outlevel >= O_DEBUG)
89 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
90 save_str(xmit_names, lname, XMIT_ACCEPT);
95 static void find_server_names(const char *hdr,
97 struct idlist **xmit_names)
98 /* parse names out of a RFC822 header into an ID list */
99 /* hdr: RFC822 header in question */
100 /* ctl: list of permissible aliases */
101 /* xmit_names: list of recipient names parsed out */
103 if (hdr == (char *)NULL)
109 for (cp = nxtaddr(hdr); cp != NULL; cp = nxtaddr(NULL))
114 * Handle empty address from a To: header containing only
121 * If the name of the user begins with a qmail virtual
122 * domain prefix, ignore the prefix. Doing this here
123 * means qvirtual will work either with ordinary name
124 * mapping or with a localdomains option.
126 if (ctl->server.qvirtual)
128 int sl = strlen(ctl->server.qvirtual);
130 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
134 if ((atsign = strchr((char *)cp, '@'))) {
137 /* try to match full address first, this takes
138 * precedence over localdomains and alias mappings */
139 if (map_address(cp, ctl, xmit_names))
143 * Does a trailing segment of the hostname match something
144 * on the localdomains list? If so, save the whole name
147 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
150 rhs = atsign + (strlen(atsign) - strlen(idp->id));
152 (rhs[-1] == '.' || rhs[-1] == '@') &&
153 strcasecmp(rhs, idp->id) == 0)
155 if (outlevel >= O_DEBUG)
156 report(stdout, GT_("passed through %s matching %s\n"),
158 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
164 /* if we matched a local domain, idp != NULL */
168 * Check to see if the right-hand part is an alias
169 * or MX equivalent of the mailserver. If it's
170 * not, skip this name. If it is, we'll keep
171 * going and try to find a mapping to a client name.
173 if (!is_host_alias(atsign+1, ctl, &ai0))
175 save_str(xmit_names, cp, XMIT_REJECT);
181 map_name(cp, ctl, xmit_names);
189 * Return zero on a syntactically invalid address, nz on a valid one.
191 * This used to be strchr(a, '.'), but it turns out that lines like this
193 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
194 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
196 * are not uncommon. So now we just check that the following token is
197 * not itself an email address.
199 #define VALID_ADDRESS(a) !strchr(a, '@')
201 static char *parse_received(struct query *ctl, char *bufp)
202 /* try to extract real address from the Received line */
203 /* If a valid Received: line is found, we return the full address in
204 * a buffer which can be parsed from nxtaddr(). This is to ansure that
205 * the local domain part of the address can be passed along in
206 * find_server_names() if it contains one.
207 * Note: We should return a dummy header containing the address
208 * which makes nxtaddr() behave correctly.
211 char *base, *ok = (char *)NULL;
212 static char rbuf[HOSTLEN + USERNAMELEN + 4];
213 struct addrinfo *ai0;
215 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
218 * Try to extract the real envelope addressee. We look here
219 * specifically for the mailserver's Received line.
220 * Note: this will only work for sendmail, or an MTA that
221 * shares sendmail's convention for embedding the envelope
222 * address in the Received line. Sendmail itself only
223 * does this when the mail has a single recipient.
225 if (outlevel >= O_DEBUG)
226 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
228 /* search for whitepace-surrounded "by" followed by valid address */
229 for (base = bufp; ; base = ok + 2)
231 if (!(ok = strstr(base, "by")))
233 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
239 /* extract space-delimited token after "by" */
240 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
243 for (; *sp && !isspace((unsigned char)*sp); sp++)
247 /* look for valid address */
248 if (VALID_ADDRESS(rbuf))
251 ok = sp - 1; /* arrange to skip this token */
257 * If it's a DNS name of the mail server, look for the
258 * recipient name after a following "for". Otherwise
261 if (is_host_alias(rbuf, ctl, &ai0))
263 if (outlevel >= O_DEBUG)
265 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
269 if (outlevel >= O_DEBUG)
271 GT_("line rejected, %s is not an alias of the mailserver\n"),
276 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
277 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
279 if (!(ok = strstr(base, "for")))
281 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
287 /* extract space-delimited token after "for" */
288 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
291 for (; !isspace((unsigned char)*sp); sp++)
295 if (strchr(rbuf, '@'))
298 ok = sp - 1; /* arrange to skip this token */
303 flag want_gt = FALSE;
306 /* char after "for" could be space or a continuation newline */
307 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
310 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
311 RBUF_WRITE(' '); /* with nxtaddr()... */
317 while (*sp == '@') /* skip routes */
318 while (*sp && *sp++ != ':')
321 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
323 if (!isspace((unsigned char)*sp))
330 /* uh oh -- whitespace here can't be right! */
336 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
344 if (outlevel >= O_DEBUG)
345 report(stdout, GT_("no Received address found\n"));
350 if (outlevel >= O_DEBUG) {
351 char *lf = rbuf + strlen(rbuf)-1;
353 if (outlevel >= O_DEBUG)
354 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
361 /* shared by readheaders and readbody */
362 static int sizeticker;
364 /** Print ticker based on a amount of data transferred of \a bytes.
365 * Increments \a *tickervar by \a bytes, and if it exceeds
366 * \a SIZETICKER, print a dot and reduce *tickervar by \a SIZETICKER. */
367 static void print_ticker(int *tickervar, int bytes)
370 while (*tickervar >= SIZETICKER)
372 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
377 *tickervar -= SIZETICKER;
381 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
382 || ((s)[0] == '\n' && (s)[1] == '\0'))
384 static int end_of_header (const char *s)
385 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
389 return (s[0] == '\n' && s[1] == '\0');
392 int readheaders(int sock,
397 flag *suppress_readbody)
398 /* read message headers and ship to SMTP or MDA */
399 /* sock: to which the server is connected */
400 /* fetchlen: length of message according to fetch response */
401 /* reallen: length of message according to getsizes */
402 /* ctl: query control record */
403 /* num: index of message */
404 /* suppress_readbody: whether call to readbody() should be supressed */
409 struct addrblk *next;
411 struct addrblk *to_addrchain = NULL;
412 struct addrblk **to_chainptr = &to_addrchain;
413 struct addrblk *resent_to_addrchain = NULL;
414 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
416 char buf[MSGBUFSIZE+1];
417 int from_offs, reply_to_offs, resent_from_offs;
418 int app_from_offs, sender_offs, resent_sender_offs;
420 char *received_for, *rcv, *cp;
421 static char *delivered_to = NULL;
422 int n, oldlen, ch, remaining, skipcount;
424 int delivered_to_count;
426 flag no_local_matches = FALSE;
428 int olderrs, good_addresses, bad_addresses;
429 int retain_mail = 0, refuse_mail = 0;
430 flag already_has_return_path = FALSE;
434 msgblk.return_path[0] = '\0';
435 olderrs = ctl->errcount;
437 /* read message headers */
438 msgblk.reallen = reallen;
441 * We used to free the header block unconditionally at the end of
442 * readheaders, but it turns out that if close_sink() hits an error
443 * condition the code for sending bouncemail will actually look
444 * at the freed storage and coredump...
446 xfree(msgblk.headers);
447 free_str_list(&msgblk.recipients);
450 /* initially, no message digest */
451 memset(ctl->digest, '\0', sizeof(ctl->digest));
454 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
455 sender_offs = resent_sender_offs = env_offs = -1;
459 delivered_to_count = 0;
462 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
466 line = (char *)xmalloc(sizeof(buf));
473 set_timeout(mytimeout);
474 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
482 * Smash out any NULs, they could wreak havoc later on.
483 * Some network stacks seem to generate these at random,
484 * especially (according to reports) at the beginning of the
485 * first read. NULs are illegal in RFC822 format.
487 for (sp = tp = buf; sp < buf + n; sp++)
500 * Try to gracefully handle the case where the length of a
501 * line exceeds MSGBUFSIZE.
503 if (n && buf[n-1] != '\n')
505 rline = (char *) realloc(line, linelen + 1);
512 memcpy(line + linelen - n, buf, n);
513 line[linelen] = '\0';
514 ch = ' '; /* So the next iteration starts */
518 /* lines may not be properly CRLF terminated; fix this for qmail */
519 /* we don't want to overflow the buffer here */
520 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
523 rline = (char *) realloc(line, linelen + 2);
530 memcpy(line + linelen - n, buf, n - 1);
531 tcp = line + linelen - 1;
540 rline = (char *) realloc(line, linelen + 1);
547 memcpy(line + linelen - n, buf, n + 1);
550 /* check for end of headers */
551 if (end_of_header(line))
553 if (linelen != strlen (line))
556 goto process_headers;
560 * Check for end of message immediately. If one of your folders
561 * has been mangled, the delimiter may occur directly after the
564 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
566 if (outlevel > O_SILENT)
568 GT_("message delimiter found while scanning headers\n"));
569 if (suppress_readbody)
570 *suppress_readbody = TRUE;
571 if (linelen != strlen (line))
574 goto process_headers;
578 * At least one brain-dead website (netmind.com) is known to
579 * send out robotmail that's missing the RFC822 delimiter blank
580 * line before the body! Without this check fetchmail segfaults.
581 * With it, we treat such messages as spam and refuse them.
583 * Frederic Marchal reported in February 2006 that hotmail
584 * or something improperly wrapped a very long TO header
585 * (wrapped without inserting whitespace in the continuation
586 * line) and found that this code thus refused a message
587 * that should have been delivered.
589 * XXX FIXME: we should probably wrap the message up as
590 * message/rfc822 attachment and forward to postmaster (Rob
593 if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
595 if (linelen != strlen (line))
597 if (outlevel > O_SILENT)
599 GT_("incorrect header line found while scanning headers\n"));
600 if (outlevel >= O_VERBOSE)
601 report (stdout, GT_("line: %s"), line);
605 /* check for RFC822 continuations */
606 set_timeout(mytimeout);
610 (ch == ' ' || ch == '\t'); /* continuation to next line? */
612 /* write the message size dots */
613 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
615 print_ticker(&sizeticker, linelen);
619 * Decode MIME encoded headers. We MUST do this before
620 * looking at the Content-Type / Content-Transfer-Encoding
621 * headers (RFC 2046).
623 if ( ctl->mimedecode )
627 /* the line is now shorter. So we retrace back till we find our terminating
628 * combination \n\0, we move backwards to make sure that we don't catch som
629 * \n\0 stored in the decoded part of the message */
630 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
631 if(tcp > line) linelen = tcp - line;
635 /* skip processing if we are going to retain or refuse this mail */
636 if (retain_mail || refuse_mail)
642 /* we see an ordinary (non-header, non-message-delimiter) line */
643 if (linelen != strlen (line))
647 * The University of Washington IMAP server (the reference
648 * implementation of IMAP4 written by Mark Crispin) relies
649 * on being able to keep base-UID information in a special
650 * message at the head of the mailbox. This message should
651 * neither be deleted nor forwarded.
653 * An example for such a message is (keep this in so people
654 * find it when looking where the special code is to handle the
657 * From MAILER-DAEMON Wed Nov 23 11:38:42 2005
658 * Date: 23 Nov 2005 11:38:42 +0100
659 * From: Mail System Internal Data <MAILER-DAEMON@mail.example.org>
660 * Subject: DON'T DELETE THIS MESSAGE -- FOLDER INTERNAL DATA
661 * Message-ID: <1132742322@mail.example.org>
662 * X-IMAP: 1132742306 0000000001
665 * This text is part of the internal format of your mail folder, and is not
666 * a real message. It is created automatically by the mail system software.
667 * If deleted, important folder data will be lost, and it will be re-created
668 * with the data reset to initial values.
670 * This message is only visible if a POP3 server that is unaware
671 * of these UWIMAP messages is used besides UWIMAP or PINE.
673 * We will just check if the first message in the mailbox has an
678 * We disable this check under POP2 because there's no way to
679 * prevent deletion of the message. So at least we ought to
680 * forward it to the user so he or she will have some clue
681 * that things have gone awry.
683 if (servport("pop2") != servport(protocol->service))
684 #endif /* POP2_ENABLE */
685 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
692 * This code prevents fetchmail from becoming an accessory after
693 * the fact to upstream sendmails with the `E' option on. It also
694 * copes with certain brain-dead POP servers (like NT's) that pass
695 * through Unix from_ lines.
697 * Either of these bugs can result in a non-RFC822 line at the
698 * beginning of the headers. If fetchmail just passes it
699 * through, the client listener may think the message has *no*
700 * headers (since the first) line it sees doesn't look
701 * RFC822-conformant) and fake up a set.
703 * What the user would see in this case is bogus (synthesized)
704 * headers, followed by a blank line, followed by the >From,
705 * followed by the real headers, followed by a blank line,
708 * We forestall this lossage by tossing anything that looks
709 * like an escaped or passed-through From_ line in headers.
710 * These aren't RFC822 so our conscience is clear...
712 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
719 * We remove all Delivered-To: headers if dropdelivered is set
720 * - special care must be taken if Delivered-To: is also used
721 * as envelope at the same time.
723 * This is to avoid false mail loops errors when delivering
724 * local messages to and from a Postfix or qmail mailserver.
726 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
729 ctl->server.envelope == STRING_DISABLED ||
730 !ctl->server.envelope ||
731 strcasecmp(ctl->server.envelope, "Delivered-To") ||
732 delivered_to_count != ctl->server.envskip)
736 delivered_to_count++;
741 * If we see a Status line, it may have been inserted by an MUA
742 * on the mail host, or it may have been inserted by the server
743 * program after the headers in the transaction stream. This
744 * can actually hose some new-mail notifiers such as xbuffy,
745 * which assumes any Status line came from a *local* MDA and
746 * therefore indicates that the message has been seen.
748 * Some buggy POP servers (including at least the 3.3(20)
749 * version of the one distributed with IMAP) insert empty
750 * Status lines in the transaction stream; we'll chuck those
751 * unconditionally. Nonempty ones get chucked if the user
752 * turns on the dropstatus flag.
757 if (!strncasecmp(line, "Status:", 7))
759 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
764 while (*cp && isspace((unsigned char)*cp)) cp++;
765 if (!*cp || ctl->dropstatus)
774 line = reply_hack(line, ctl->server.truename, &linelen);
777 * OK, this is messy. If we're forwarding by SMTP, it's the
778 * SMTP-receiver's job (according to RFC821, page 22, section
779 * 4.1.1) to generate a Return-Path line on final delivery.
780 * The trouble is, we've already got one because the
781 * mailserver's SMTP thought *it* was responsible for final
784 * Stash away the contents of Return-Path (as modified by reply_hack)
785 * for use in generating MAIL FROM later on, then prevent the header
786 * from being saved with the others. In effect, we strip it off here.
788 * If the SMTP server conforms to the standards, and fetchmail gets the
789 * envelope sender from the Return-Path, the new Return-Path should be
790 * exactly the same as the original one.
792 * We do *not* want to ignore empty Return-Path headers. These should
793 * be passed through as a way of indicating that a message should
794 * not trigger bounces if delivery fails. What we *do* need to do is
795 * make sure we never try to rewrite such a blank Return-Path. We
796 * handle this with a check for <> in the rewrite logic above.
798 * Also, if an email has multiple Return-Path: headers, we only
799 * read the first occurance, as some spam email has more than one
803 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
805 already_has_return_path = TRUE;
806 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
808 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
809 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
819 msgblk.headers = (char *)xmalloc(oldlen + 1);
820 (void) memcpy(msgblk.headers, line, linelen);
821 msgblk.headers[oldlen] = '\0';
823 line = msgblk.headers;
830 newlen = oldlen + linelen;
831 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
832 if (newhdrs == NULL) {
836 msgblk.headers = newhdrs;
837 memcpy(msgblk.headers + oldlen, line, linelen);
838 msgblk.headers[newlen] = '\0';
840 line = msgblk.headers + oldlen;
844 /* find offsets of various special headers */
845 if (!strncasecmp("From:", line, 5))
846 from_offs = (line - msgblk.headers);
847 else if (!strncasecmp("Reply-To:", line, 9))
848 reply_to_offs = (line - msgblk.headers);
849 else if (!strncasecmp("Resent-From:", line, 12))
850 resent_from_offs = (line - msgblk.headers);
851 else if (!strncasecmp("Apparently-From:", line, 16))
852 app_from_offs = (line - msgblk.headers);
854 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
856 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
857 * that Sender: *doesn't* have to be a working email address.
859 * The definition of the Sender header in RFC822 says, in
860 * part, "The Sender mailbox specification includes a word
861 * sequence which must correspond to a specific agent (i.e., a
862 * human user or a computer program) rather than a standard
863 * address." That implies that the contents of the Sender
864 * field don't need to be a legal email address at all So
865 * ignore any Sender or Resent-Sender lines unless they
868 * (RFC2822 says the contents of Sender must be a valid mailbox
869 * address, which is also what RFC822 4.4.4 implies.)
871 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
872 sender_offs = (line - msgblk.headers);
873 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
874 resent_sender_offs = (line - msgblk.headers);
877 else if (!strncasecmp("Message-Id:", line, 11))
879 if (ctl->server.uidl)
883 line[IDLEN+12] = 0; /* prevent stack overflow */
884 sscanf(line+12, "%s", id);
885 if (!str_find( &ctl->newsaved, num))
887 struct idlist *newl = save_str(&ctl->newsaved,id,UID_SEEN);
888 newl->val.status.num = num;
892 #endif /* __UNUSED__ */
894 /* if multidrop is on, gather addressee headers */
897 if (!strncasecmp("To:", line, 3)
898 || !strncasecmp("Cc:", line, 3)
899 || !strncasecmp("Bcc:", line, 4)
900 || !strncasecmp("Apparently-To:", line, 14))
902 *to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
903 (*to_chainptr)->offset = (line - msgblk.headers);
904 to_chainptr = &(*to_chainptr)->next;
908 else if (!strncasecmp("Resent-To:", line, 10)
909 || !strncasecmp("Resent-Cc:", line, 10)
910 || !strncasecmp("Resent-Bcc:", line, 11))
912 *resent_to_chainptr = (struct addrblk *)xmalloc(sizeof(struct addrblk));
913 (*resent_to_chainptr)->offset = (line - msgblk.headers);
914 resent_to_chainptr = &(*resent_to_chainptr)->next;
915 *resent_to_chainptr = NULL;
918 else if (ctl->server.envelope != STRING_DISABLED)
920 if (ctl->server.envelope
921 && strcasecmp(ctl->server.envelope, "Received"))
923 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
925 strlen(ctl->server.envelope)))
927 if (skipcount++ < ctl->server.envskip)
929 env_offs = (line - msgblk.headers);
932 else if (!received_for && !strncasecmp("Received:", line, 9))
934 if (skipcount++ < ctl->server.envskip)
936 received_for = parse_received(ctl, line);
951 * This is the duplicate-message killer code.
953 * When mail delivered to a multidrop mailbox on the server is
954 * addressed to multiple people on the client machine, there will
955 * be one copy left in the box for each recipient. This is not a
956 * problem if we have the actual recipient address to dispatch on
957 * (e.g. because we've mined it out of sendmail trace headers, or
958 * a qmail Delivered-To line, or a declared sender envelope line).
960 * But if we're mining addressees out of the To/Cc/Bcc fields, and
961 * if the mail is addressed to N people, each recipient will
962 * get N copies. This is bad when N > 1.
964 * Foil this by suppressing all but one copy of a message with a
965 * given set of headers.
967 * Note: This implementation only catches runs of successive
968 * messages with the same ID, but that should be good
969 * enough. A more general implementation would have to store
970 * ever-growing lists of seen message-IDs; in a long-running
971 * daemon this would turn into a memory leak even if the
972 * implementation were perfect.
974 * Don't mess with this code casually. It would be way too easy
975 * to break it in a way that blackholed mail. Better to pass
976 * the occasional duplicate than to do that...
979 * The real fix however is to insist on Delivered-To: or similar
980 * headers and require that one copy per recipient be dropped.
981 * Everything else breaks sooner or later.
983 if (MULTIDROP(ctl) && msgblk.headers)
988 MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
989 MD5Final(ctl->digest, &context);
991 if (!received_for && env_offs == -1 && !delivered_to)
994 * Hmmm...can MD5 ever yield all zeroes as a hash value?
995 * If so there is a one in 18-quadrillion chance this
996 * code will incorrectly nuke the first message.
998 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
1001 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
1005 * Hack time. If the first line of the message was blank, with no headers
1006 * (this happens occasionally due to bad gatewaying software) cons up
1007 * a set of fake headers.
1009 * If you modify the fake header template below, be sure you don't
1010 * make either From or To address @-less, otherwise the reply_hack
1011 * logic will do bad things.
1013 if (msgblk.headers == (char *)NULL)
1015 snprintf(buf, sizeof(buf),
1016 "From: FETCHMAIL-DAEMON\r\n"
1018 "Subject: Headerless mail from %s's mailbox on %s\r\n",
1019 user, fetchmailhost, ctl->remotename, ctl->server.truename);
1020 msgblk.headers = xstrdup(buf);
1024 * We can now process message headers before reading the text.
1025 * In fact we have to, as this will tell us where to forward to.
1028 /* Check for MIME headers indicating possible 8-bit data */
1029 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
1032 if (ctl->server.sdps && sdps_envfrom)
1034 /* We have the real envelope return-path, stored out of band by
1035 * SDPS - that's more accurate than any header is going to be.
1037 strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
1040 #endif /* SDPS_ENABLE */
1042 * If there is a Return-Path address on the message, this was
1043 * almost certainly the MAIL FROM address given the originating
1044 * sendmail. This is the best thing to use for logging the
1045 * message origin (it sets up the right behavior for bounces and
1046 * mailing lists). Otherwise, fall down to the next available
1047 * envelope address (which is the most probable real sender).
1048 * *** The order is important! ***
1049 * This is especially useful when receiving mailing list
1050 * messages in multidrop mode. if a local address doesn't
1051 * exist, the bounce message won't be returned blindly to the
1052 * author or to the list itself but rather to the list manager
1053 * (ex: specified by "Sender:") which is much less annoying. This
1054 * is true for most mailing list packages.
1056 if( !msgblk.return_path[0] ){
1058 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
1059 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
1060 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
1061 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
1062 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
1063 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
1064 /* multi-line MAIL FROM addresses confuse SMTP terribly */
1065 if (ap && !strchr(ap, '\n')) {
1066 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
1067 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1071 /* cons up a list of local recipients */
1072 msgblk.recipients = (struct idlist *)NULL;
1073 accept_count = reject_count = 0;
1074 /* is this a multidrop box? */
1078 if (ctl->server.sdps && sdps_envto)
1080 /* We have the real envelope recipient, stored out of band by
1081 * SDPS - that's more accurate than any header is going to be.
1083 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1086 #endif /* SDPS_ENABLE */
1087 if (env_offs > -1) /* We have the actual envelope addressee */
1088 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1089 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1090 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1092 find_server_names(delivered_to, ctl, &msgblk.recipients);
1093 xfree(delivered_to);
1095 else if (received_for)
1097 * We have the Received for addressee.
1098 * It has to be a mailserver address, or we
1099 * wouldn't have got here.
1100 * We use find_server_names() to let local
1101 * hostnames go through.
1103 find_server_names(received_for, ctl, &msgblk.recipients);
1107 * We haven't extracted the envelope address.
1108 * So check all the "Resent-To" header addresses if
1109 * they exist. If and only if they don't, consider
1110 * the "To" addresses.
1112 register struct addrblk *nextptr;
1113 if (resent_to_addrchain) {
1114 /* delete the "To" chain and substitute it
1115 * with the "Resent-To" list
1117 while (to_addrchain) {
1118 nextptr = to_addrchain->next;
1120 to_addrchain = nextptr;
1122 to_addrchain = resent_to_addrchain;
1123 resent_to_addrchain = NULL;
1125 /* now look for remaining adresses */
1126 while (to_addrchain) {
1127 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1128 nextptr = to_addrchain->next;
1130 to_addrchain = nextptr;
1135 no_local_matches = TRUE;
1136 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1137 if (outlevel >= O_DEBUG)
1139 GT_("no local matches, forwarding to %s\n"),
1143 else /* it's a single-drop box, use first localname */
1144 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1148 * Time to either address the message or decide we can't deliver it yet.
1150 if (ctl->errcount > olderrs) /* there were DNS errors above */
1152 if (outlevel >= O_DEBUG)
1154 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1155 return(PS_TRANSIENT);
1159 /* set up stuffline() so we can deliver the message body through it */
1160 if ((n = open_sink(ctl, &msgblk,
1161 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1169 * Some server/sendmail combinations cause problems when our
1170 * synthetic Received line is before the From header. Cope
1173 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1174 rcv = msgblk.headers;
1175 /* handle ">Received:" lines too */
1176 while (rcv > msgblk.headers && rcv[-1] != '\n')
1178 if (rcv > msgblk.headers)
1183 n = stuffline(ctl, msgblk.headers);
1186 if (!run.invisible && n != -1)
1188 /* utter any per-message Received information we need here */
1189 if (ctl->server.trueaddr) {
1193 e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1194 saddr, sizeof(saddr), NULL, 0,
1197 snprintf(saddr, sizeof(saddr), "(%-.*s)", (int)(sizeof(saddr) - 3), gai_strerror(e));
1198 snprintf(buf, sizeof(buf),
1199 "Received: from %s [%s]\r\n",
1200 ctl->server.truename, saddr);
1202 snprintf(buf, sizeof(buf),
1203 "Received: from %s\r\n", ctl->server.truename);
1205 n = stuffline(ctl, buf);
1209 * We SHOULD (RFC-2821 sec. 4.4/p. 53) make sure to only use
1210 * IANA registered protocol names here.
1212 snprintf(buf, sizeof(buf),
1213 "\tby %s with %s (fetchmail-%s",
1217 if (ctl->server.tracepolls)
1219 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1220 " polling %s account %s",
1221 ctl->server.pollname,
1224 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1228 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1229 n = stuffline(ctl, buf);
1233 if (good_addresses == 0)
1235 snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1236 rcpt_address (ctl, run.postmaster, 0));
1238 else if (good_addresses == 1)
1240 for (idp = msgblk.recipients; idp; idp = idp->next)
1241 if (idp->val.status.mark == XMIT_ACCEPT)
1242 break; /* only report first address */
1243 snprintf(buf+1, sizeof(buf)-1,
1244 "for <%s>", rcpt_address (ctl, idp->id, 1));
1245 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1247 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1252 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1254 n = stuffline(ctl, buf);
1260 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1264 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1268 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
1271 /* write error notifications */
1272 if (no_local_matches || has_nuls || bad_addresses)
1275 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1278 strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1279 if (no_local_matches)
1281 if (reject_count != 1)
1282 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1285 for (idp = msgblk.recipients; idp; idp = idp->next)
1286 if (idp->val.status.mark == XMIT_REJECT)
1288 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1289 GT_("recipient address %s didn't match any local name"), idp->id);
1295 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1296 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1297 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1298 GT_("message has embedded NULs"));
1303 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1304 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1305 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1306 GT_("SMTP listener rejected local recipient addresses: "));
1307 errlen = strlen(errhd);
1308 for (idp = msgblk.recipients; idp; idp = idp->next)
1309 if (idp->val.status.mark == XMIT_RCPTBAD)
1310 errlen += strlen(idp->id) + 2;
1312 errmsg = (char *)xmalloc(errlen + 3);
1313 strcpy(errmsg, errhd);
1314 for (idp = msgblk.recipients; idp; idp = idp->next)
1315 if (idp->val.status.mark == XMIT_RCPTBAD)
1317 strcat(errmsg, idp->id);
1319 strcat(errmsg, ", ");
1324 strcat(errmsg, "\r\n");
1326 /* ship out the error line */
1327 stuffline(ctl, errmsg);
1329 if (errmsg != errhd)
1333 /* issue the delimiter line */
1338 n = stuffline(ctl, buf);
1340 if (n == strlen(buf))
1346 int readbody(int sock, struct query *ctl, flag forward, int len)
1347 /* read and dispose of a message body presented on sock */
1348 /* ctl: query control record */
1349 /* sock: to which the server is connected */
1350 /* len: length of message */
1351 /* forward: TRUE to forward */
1354 char buf[MSGBUFSIZE+4];
1356 flag issoftline = FALSE;
1359 * Pass through the text lines in the body.
1361 * Yes, this wants to be ||, not &&. The problem is that in the most
1362 * important delimited protocol, POP3, the length is not reliable.
1363 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1364 * So, for delimited protocols we need to ignore the length here and
1365 * instead drop out of the loop with a break statement when we see
1366 * the message delimiter.
1368 while (protocol->delimited || len > 0)
1370 set_timeout(mytimeout);
1371 /* XXX FIXME: for undelimited protocols that ship the size, such
1372 * as IMAP, we might want to use the count of remaining characters
1373 * instead of the buffer size -- not for fetchmail 6.3.X though */
1374 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1382 /* write the message size dots */
1385 print_ticker(&sizeticker, linelen);
1388 /* Mike Jones, Manchester University, 2006:
1389 * "To fix IMAP MIME Messages in which fetchmail adds the remainder of
1390 * the IMAP packet including the ')' character (part of the IMAP)
1391 * Protocol causing the addition of an extra MIME boundary locally."
1393 * However, we shouldn't do this for delimited protocols:
1394 * many POP3 servers (Microsoft, qmail) goof up message sizes
1395 * so we might end truncating messages prematurely.
1397 if (!protocol->delimited && linelen > len) {
1403 /* check for end of message */
1404 if (protocol->delimited && *inbufp == '.')
1406 if (EMPTYLINE(inbufp+1))
1409 msgblk.msglen--; /* subtract the size of the dot escape */
1412 msgblk.msglen += linelen;
1414 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1415 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1416 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1419 * Soft linebreak, but less than 200 bytes left in
1420 * input buffer. Rather than doing a buffer overrun,
1421 * ignore the soft linebreak, NL-terminate data and
1422 * deliver what we have now.
1423 * (Who writes lines longer than 2K anyway?)
1425 *inbufp = '\n'; *(inbufp+1) = '\0';
1430 /* ship out the text line */
1431 if (forward && (!issoftline))
1436 /* guard against very long lines */
1437 buf[MSGBUFSIZE+1] = '\r';
1438 buf[MSGBUFSIZE+2] = '\n';
1439 buf[MSGBUFSIZE+3] = '\0';
1441 n = stuffline(ctl, buf);
1445 report(stdout, GT_("error writing message text\n"));
1449 else if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
1460 void init_transact(const struct method *proto)
1461 /* initialize state for the send and receive functions */
1463 suppress_tags = FALSE;
1465 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1466 protocol = (struct method *)proto;
1470 static void enshroud(char *buf)
1471 /* shroud a password in the given buffer */
1475 if (shroud[0] && (cp = strstr(buf, shroud)))
1479 sp = cp + strlen(shroud);
1487 #if defined(HAVE_STDARG_H)
1488 void gen_send(int sock, const char *fmt, ... )
1490 void gen_send(sock, fmt, va_alist)
1491 int sock; /* socket to which server is connected */
1492 const char *fmt; /* printf-style format */
1495 /* assemble command in printf(3) style and send to the server */
1497 char buf [MSGBUFSIZE+1];
1500 if (protocol->tagged && !suppress_tags)
1501 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1505 #if defined(HAVE_STDARG_H)
1510 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1513 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1514 SockWrite(sock, buf, strlen(buf));
1516 if (outlevel >= O_MONITOR)
1519 buf[strlen(buf)-2] = '\0';
1520 report(stdout, "%s> %s\n", protocol->name, buf);
1524 /** get one line of input from the server */
1525 int gen_recv(int sock /** socket to which server is connected */,
1526 char *buf /* buffer to receive input */,
1527 int size /* length of buffer */)
1529 int oldphase = phase; /* we don't have to be re-entrant */
1531 phase = SERVER_WAIT;
1532 set_timeout(mytimeout);
1533 if (SockRead(sock, buf, size) == -1)
1537 if(is_idletimeout())
1540 return(PS_IDLETIMEOUT);
1548 if (buf[strlen(buf)-1] == '\n')
1549 buf[strlen(buf)-1] = '\0';
1550 if (buf[strlen(buf)-1] == '\r')
1551 buf[strlen(buf)-1] = '\0';
1552 if (outlevel >= O_MONITOR)
1553 report(stdout, "%s< %s\n", protocol->name, buf);
1559 #if defined(HAVE_STDARG_H)
1560 int gen_transact(int sock, const char *fmt, ... )
1562 int gen_transact(int sock, fmt, va_alist)
1563 int sock; /* socket to which server is connected */
1564 const char *fmt; /* printf-style format */
1567 /* assemble command in printf(3) style, send to server, accept a response */
1570 char buf [MSGBUFSIZE+1];
1572 int oldphase = phase; /* we don't have to be re-entrant */
1574 phase = SERVER_WAIT;
1576 if (protocol->tagged && !suppress_tags)
1577 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1581 #if defined(HAVE_STDARG_H)
1586 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1589 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1590 ok = SockWrite(sock, buf, strlen(buf));
1591 if (ok == -1 || (size_t)ok != strlen(buf)) {
1592 /* short write, bail out */
1596 if (outlevel >= O_MONITOR)
1599 buf[strlen(buf)-2] = '\0';
1600 report(stdout, "%s> %s\n", protocol->name, buf);
1603 /* we presume this does its own response echoing */
1604 ok = (protocol->parse_response)(sock, buf);
1610 /* transact.c ends here */