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 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
59 /* add given name to xmit_names if it matches declared localnames */
60 /* name: name to map */
61 /* ctl: list of permissible aliases */
62 /* xmit_names: list of recipient names parsed out */
67 lname = idpair_find(&ctl->localnames, name+off);
68 if (!lname && ctl->wildcard)
71 if (lname != (char *)NULL)
73 if (outlevel >= O_DEBUG)
74 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
75 save_str(xmit_names, lname, XMIT_ACCEPT);
80 static void find_server_names(const char *hdr,
82 struct idlist **xmit_names)
83 /* parse names out of a RFC822 header into an ID list */
84 /* hdr: RFC822 header in question */
85 /* ctl: list of permissible aliases */
86 /* xmit_names: list of recipient names parsed out */
88 if (hdr == (char *)NULL)
94 for (cp = nxtaddr((const unsigned char *)hdr);
101 * Handle empty address from a To: header containing only
108 * If the name of the user begins with a qmail virtual
109 * domain prefix, ignore the prefix. Doing this here
110 * means qvirtual will work either with ordinary name
111 * mapping or with a localdomains option.
113 if (ctl->server.qvirtual)
115 int sl = strlen(ctl->server.qvirtual);
117 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
121 if ((atsign = strchr((char *)cp, '@'))) {
125 * Does a trailing segment of the hostname match something
126 * on the localdomains list? If so, save the whole name
129 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
132 rhs = atsign + (strlen(atsign) - strlen((char *)idp->id));
134 (rhs[-1] == '.' || rhs[-1] == '@') &&
135 strcasecmp(rhs, (char *)idp->id) == 0)
137 if (outlevel >= O_DEBUG)
138 report(stdout, GT_("passed through %s matching %s\n"),
140 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
146 /* if we matched a local domain, idp != NULL */
150 * Check to see if the right-hand part is an alias
151 * or MX equivalent of the mailserver. If it's
152 * not, skip this name. If it is, we'll keep
153 * going and try to find a mapping to a client name.
155 if (!is_host_alias(atsign+1, ctl))
157 save_str(xmit_names, cp, XMIT_REJECT);
163 map_name(cp, ctl, xmit_names);
171 * Return zero on a syntactically invalid address, nz on a valid one.
173 * This used to be strchr(a, '.'), but it turns out that lines like this
175 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
176 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
178 * are not uncommon. So now we just check that the following token is
179 * not itself an email address.
181 #define VALID_ADDRESS(a) !strchr(a, '@')
183 static char *parse_received(struct query *ctl, char *bufp)
184 /* try to extract real address from the Received line */
185 /* If a valid Received: line is found, we return the full address in
186 * a buffer which can be parsed from nxtaddr(). This is to ansure that
187 * the local domain part of the address can be passed along in
188 * find_server_names() if it contains one.
189 * Note: We should return a dummy header containing the address
190 * which makes nxtaddr() behave correctly.
193 char *base, *ok = (char *)NULL;
194 static char rbuf[HOSTLEN + USERNAMELEN + 4];
196 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
199 * Try to extract the real envelope addressee. We look here
200 * specifically for the mailserver's Received line.
201 * Note: this will only work for sendmail, or an MTA that
202 * shares sendmail's convention for embedding the envelope
203 * address in the Received line. Sendmail itself only
204 * does this when the mail has a single recipient.
206 if (outlevel >= O_DEBUG)
207 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
209 /* search for whitepace-surrounded "by" followed by valid address */
210 for (base = bufp; ; base = ok + 2)
212 if (!(ok = strstr(base, "by")))
214 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
220 /* extract space-delimited token after "by" */
221 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
224 for (; *sp && !isspace((unsigned char)*sp); sp++)
228 /* look for valid address */
229 if (VALID_ADDRESS(rbuf))
232 ok = sp - 1; /* arrange to skip this token */
238 * If it's a DNS name of the mail server, look for the
239 * recipient name after a following "for". Otherwise
242 if (is_host_alias(rbuf, ctl))
244 if (outlevel >= O_DEBUG)
246 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
250 if (outlevel >= O_DEBUG)
252 GT_("line rejected, %s is not an alias of the mailserver\n"),
257 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
258 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
260 if (!(ok = strstr(base, "for")))
262 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
268 /* extract space-delimited token after "for" */
269 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
272 for (; !isspace((unsigned char)*sp); sp++)
276 if (strchr(rbuf, '@'))
279 ok = sp - 1; /* arrange to skip this token */
284 flag want_gt = FALSE;
287 /* char after "for" could be space or a continuation newline */
288 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
291 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
292 RBUF_WRITE(' '); /* with nxtaddr()... */
298 while (*sp == '@') /* skip routes */
299 while (*sp && *sp++ != ':')
302 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
304 if (!isspace((unsigned char)*sp))
311 /* uh oh -- whitespace here can't be right! */
317 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
325 if (outlevel >= O_DEBUG)
326 report(stdout, GT_("no Received address found\n"));
331 if (outlevel >= O_DEBUG) {
332 char *lf = rbuf + strlen(rbuf)-1;
334 if (outlevel >= O_DEBUG)
335 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
342 /* shared by readheaders and readbody */
343 static int sizeticker;
345 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
346 || ((s)[0] == '\n' && (s)[1] == '\0'))
348 static int end_of_header (const char *s)
349 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
353 return (s[0] == '\n' && s[1] == '\0');
356 int readheaders(int sock,
361 flag *suppress_readbody)
362 /* read message headers and ship to SMTP or MDA */
363 /* sock: to which the server is connected */
364 /* fetchlen: length of message according to fetch response */
365 /* reallen: length of message according to getsizes */
366 /* ctl: query control record */
367 /* num: index of message */
368 /* suppress_readbody: whether call to readbody() should be supressed */
373 struct addrblk *next;
375 struct addrblk *to_addrchain = NULL;
376 struct addrblk **to_chainptr = &to_addrchain;
377 struct addrblk *resent_to_addrchain = NULL;
378 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
380 char buf[MSGBUFSIZE+1];
381 int from_offs, reply_to_offs, resent_from_offs;
382 int app_from_offs, sender_offs, resent_sender_offs;
384 char *received_for, *rcv, *cp;
385 static char *delivered_to = NULL;
386 int n, oldlen, ch, remaining, skipcount;
388 int delivered_to_count;
390 flag no_local_matches = FALSE;
392 int olderrs, good_addresses, bad_addresses;
393 int retain_mail = 0, refuse_mail = 0;
394 flag already_has_return_path = FALSE;
398 msgblk.return_path[0] = '\0';
399 olderrs = ctl->errcount;
401 /* read message headers */
402 msgblk.reallen = reallen;
405 * We used to free the header block unconditionally at the end of
406 * readheaders, but it turns out that if close_sink() hits an error
407 * condition the code for sending bouncemail will actually look
408 * at the freed storage and coredump...
411 free(msgblk.headers);
412 free_str_list(&msgblk.recipients);
416 /* initially, no message digest */
417 memset(ctl->digest, '\0', sizeof(ctl->digest));
419 msgblk.headers = received_for = delivered_to = NULL;
420 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
421 sender_offs = resent_sender_offs = env_offs = -1;
425 delivered_to_count = 0;
428 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
431 int overlong = FALSE; /* XXX FIXME: this is unused */
433 line = xmalloc(sizeof(buf));
440 set_timeout(mytimeout);
441 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
444 free(msgblk.headers);
445 msgblk.headers = NULL;
451 * Smash out any NULs, they could wreak havoc later on.
452 * Some network stacks seem to generate these at random,
453 * especially (according to reports) at the beginning of the
454 * first read. NULs are illegal in RFC822 format.
456 for (sp = tp = buf; sp < buf + n; sp++)
469 * Try to gracefully handle the case where the length of a
470 * line exceeds MSGBUFSIZE.
472 if (n && buf[n-1] != '\n')
475 rline = (char *) realloc(line, linelen + 1);
482 memcpy(line + linelen - n, buf, n);
483 line[linelen] = '\0';
484 ch = ' '; /* So the next iteration starts */
488 /* lines may not be properly CRLF terminated; fix this for qmail */
489 /* we don't want to overflow the buffer here */
490 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
493 rline = (char *) realloc(line, linelen + 2);
500 memcpy(line + linelen - n, buf, n - 1);
501 tcp = line + linelen - 1;
510 rline = (char *) realloc(line, linelen + 1);
517 memcpy(line + linelen - n, buf, n + 1);
520 /* check for end of headers */
521 if (end_of_header(line))
523 if (linelen != strlen (line))
526 goto process_headers;
530 * Check for end of message immediately. If one of your folders
531 * has been mangled, the delimiter may occur directly after the
534 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
536 if (outlevel > O_SILENT)
538 GT_("message delimiter found while scanning headers\n"));
539 if (suppress_readbody)
540 *suppress_readbody = TRUE;
541 if (linelen != strlen (line))
544 goto process_headers;
548 * At least one brain-dead website (netmind.com) is known to
549 * send out robotmail that's missing the RFC822 delimiter blank
550 * line before the body! Without this check fetchmail segfaults.
551 * With it, we treat such messages as spam and refuse them.
553 if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
555 if (linelen != strlen (line))
557 if (outlevel > O_SILENT)
559 GT_("incorrect header line found while scanning headers\n"));
560 if (outlevel >= O_VERBOSE)
561 report (stdout, GT_("line: %s"), line);
565 /* check for RFC822 continuations */
566 set_timeout(mytimeout);
570 (ch == ' ' || ch == '\t'); /* continuation to next line? */
572 /* write the message size dots */
573 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
575 sizeticker += linelen;
576 while (sizeticker >= SIZETICKER)
578 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
583 sizeticker -= SIZETICKER;
587 * Decode MIME encoded headers. We MUST do this before
588 * looking at the Content-Type / Content-Transfer-Encoding
589 * headers (RFC 2046).
591 if ( ctl->mimedecode )
595 /* the line is now shorter. So we retrace back till we find our terminating
596 * combination \n\0, we move backwards to make sure that we don't catch som
597 * \n\0 stored in the decoded part of the message */
598 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
599 if(tcp > line) linelen = tcp - line;
603 /* skip processing if we are going to retain or refuse this mail */
604 if (retain_mail || refuse_mail)
610 /* we see an ordinary (non-header, non-message-delimiter line */
611 if (linelen != strlen (line))
615 * The University of Washington IMAP server (the reference
616 * implementation of IMAP4 written by Mark Crispin) relies
617 * on being able to keep base-UID information in a special
618 * message at the head of the mailbox. This message should
619 * neither be deleted nor forwarded.
623 * We disable this check under POP2 because there's no way to
624 * prevent deletion of the message. So at least we ought to
625 * forward it to the user so he or she will have some clue
626 * that things have gone awry.
628 if (servport("pop2") != servport(protocol->service))
629 #endif /* POP2_ENABLE */
630 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
637 * This code prevents fetchmail from becoming an accessory after
638 * the fact to upstream sendmails with the `E' option on. It also
639 * copes with certain brain-dead POP servers (like NT's) that pass
640 * through Unix from_ lines.
642 * Either of these bugs can result in a non-RFC822 line at the
643 * beginning of the headers. If fetchmail just passes it
644 * through, the client listener may think the message has *no*
645 * headers (since the first) line it sees doesn't look
646 * RFC822-conformant) and fake up a set.
648 * What the user would see in this case is bogus (synthesized)
649 * headers, followed by a blank line, followed by the >From,
650 * followed by the real headers, followed by a blank line,
653 * We forestall this lossage by tossing anything that looks
654 * like an escaped or passed-through From_ line in headers.
655 * These aren't RFC822 so our conscience is clear...
657 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
664 * We remove all Delivered-To: headers if dropdelivered is set
665 * - special care must be taken if Delivered-To: is also used
666 * as envelope at the same time.
668 * This is to avoid false mail loops errors when delivering
669 * local messages to and from a Postfix or qmail mailserver.
671 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
674 ctl->server.envelope == STRING_DISABLED ||
675 !ctl->server.envelope ||
676 strcasecmp(ctl->server.envelope, "Delivered-To") ||
677 delivered_to_count != ctl->server.envskip)
681 delivered_to_count++;
686 * If we see a Status line, it may have been inserted by an MUA
687 * on the mail host, or it may have been inserted by the server
688 * program after the headers in the transaction stream. This
689 * can actually hose some new-mail notifiers such as xbuffy,
690 * which assumes any Status line came from a *local* MDA and
691 * therefore indicates that the message has been seen.
693 * Some buggy POP servers (including at least the 3.3(20)
694 * version of the one distributed with IMAP) insert empty
695 * Status lines in the transaction stream; we'll chuck those
696 * unconditionally. Nonempty ones get chucked if the user
697 * turns on the dropstatus flag.
702 if (!strncasecmp(line, "Status:", 7))
704 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
709 while (*cp && isspace((unsigned char)*cp)) cp++;
710 if (!*cp || ctl->dropstatus)
719 line = reply_hack(line, ctl->server.truename, &linelen);
722 * OK, this is messy. If we're forwarding by SMTP, it's the
723 * SMTP-receiver's job (according to RFC821, page 22, section
724 * 4.1.1) to generate a Return-Path line on final delivery.
725 * The trouble is, we've already got one because the
726 * mailserver's SMTP thought *it* was responsible for final
729 * Stash away the contents of Return-Path (as modified by reply_hack)
730 * for use in generating MAIL FROM later on, then prevent the header
731 * from being saved with the others. In effect, we strip it off here.
733 * If the SMTP server conforms to the standards, and fetchmail gets the
734 * envelope sender from the Return-Path, the new Return-Path should be
735 * exactly the same as the original one.
737 * We do *not* want to ignore empty Return-Path headers. These should
738 * be passed through as a way of indicating that a message should
739 * not trigger bounces if delivery fails. What we *do* need to do is
740 * make sure we never try to rewrite such a blank Return-Path. We
741 * handle this with a check for <> in the rewrite logic above.
743 * Also, if an email has multiple Return-Path: headers, we only
744 * read the first occurance, as some spam email has more than one
748 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
750 already_has_return_path = TRUE;
751 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
753 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
754 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
764 msgblk.headers = xmalloc(oldlen + 1);
765 (void) memcpy(msgblk.headers, line, linelen);
766 msgblk.headers[oldlen] = '\0';
768 line = msgblk.headers;
775 newlen = oldlen + linelen;
776 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
777 if (newhdrs == NULL) {
781 msgblk.headers = newhdrs;
782 memcpy(msgblk.headers + oldlen, line, linelen);
783 msgblk.headers[newlen] = '\0';
785 line = msgblk.headers + oldlen;
789 /* find offsets of various special headers */
790 if (!strncasecmp("From:", line, 5))
791 from_offs = (line - msgblk.headers);
792 else if (!strncasecmp("Reply-To:", line, 9))
793 reply_to_offs = (line - msgblk.headers);
794 else if (!strncasecmp("Resent-From:", line, 12))
795 resent_from_offs = (line - msgblk.headers);
796 else if (!strncasecmp("Apparently-From:", line, 16))
797 app_from_offs = (line - msgblk.headers);
799 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
801 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
802 * that Sender: *doesn't* have to be a working email address.
804 * The definition of the Sender header in RFC822 says, in
805 * part, "The Sender mailbox specification includes a word
806 * sequence which must correspond to a specific agent (i.e., a
807 * human user or a computer program) rather than a standard
808 * address." That implies that the contents of the Sender
809 * field don't need to be a legal email address at all So
810 * ignore any Sender or Resent-Sender lines unless they
813 * (RFC2822 says the contents of Sender must be a valid mailbox
814 * address, which is also what RFC822 4.4.4 implies.)
816 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
817 sender_offs = (line - msgblk.headers);
818 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
819 resent_sender_offs = (line - msgblk.headers);
822 else if (!strncasecmp("Message-Id:", line, 11))
824 if (ctl->server.uidl)
828 line[IDLEN+12] = 0; /* prevent stack overflow */
829 sscanf(line+12, "%s", id);
830 if (!str_find( &ctl->newsaved, num))
832 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
833 new->val.status.num = num;
837 #endif /* __UNUSED__ */
839 /* if multidrop is on, gather addressee headers */
842 if (!strncasecmp("To:", line, 3)
843 || !strncasecmp("Cc:", line, 3)
844 || !strncasecmp("Bcc:", line, 4)
845 || !strncasecmp("Apparently-To:", line, 14))
847 *to_chainptr = xmalloc(sizeof(struct addrblk));
848 (*to_chainptr)->offset = (line - msgblk.headers);
849 to_chainptr = &(*to_chainptr)->next;
853 else if (!strncasecmp("Resent-To:", line, 10)
854 || !strncasecmp("Resent-Cc:", line, 10)
855 || !strncasecmp("Resent-Bcc:", line, 11))
857 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
858 (*resent_to_chainptr)->offset = (line - msgblk.headers);
859 resent_to_chainptr = &(*resent_to_chainptr)->next;
860 *resent_to_chainptr = NULL;
863 else if (ctl->server.envelope != STRING_DISABLED)
865 if (ctl->server.envelope
866 && strcasecmp(ctl->server.envelope, "Received"))
868 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
870 strlen(ctl->server.envelope)))
872 if (skipcount++ < ctl->server.envskip)
874 env_offs = (line - msgblk.headers);
877 else if (!received_for && !strncasecmp("Received:", line, 9))
879 if (skipcount++ < ctl->server.envskip)
881 received_for = parse_received(ctl, line);
891 free(msgblk.headers);
892 msgblk.headers = NULL;
898 * This is the duplicate-message killer code.
900 * When mail delivered to a multidrop mailbox on the server is
901 * addressed to multiple people on the client machine, there will
902 * be one copy left in the box for each recipient. This is not a
903 * problem if we have the actual recipient address to dispatch on
904 * (e.g. because we've mined it out of sendmail trace headers, or
905 * a qmail Delivered-To line, or a declared sender envelope line).
907 * But if we're mining addressees out of the To/Cc/Bcc fields, and
908 * if the mail is addressed to N people, each recipient will
909 * get N copies. This is bad when N > 1.
911 * Foil this by suppressing all but one copy of a message with a
912 * given set of headers.
914 * Note: This implementation only catches runs of successive
915 * messages with the same ID, but that should be good
916 * enough. A more general implementation would have to store
917 * ever-growing lists of seen message-IDs; in a long-running
918 * daemon this would turn into a memory leak even if the
919 * implementation were perfect.
921 * Don't mess with this code casually. It would be way too easy
922 * to break it in a way that blackholed mail. Better to pass
923 * the occasional duplicate than to do that...
930 MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
931 MD5Final(ctl->digest, &context);
933 if (!received_for && env_offs == -1 && !delivered_to)
936 * Hmmm...can MD5 ever yield all zeroes as a hash value?
937 * If so there is a one in 18-quadrillion chance this
938 * code will incorrectly nuke the first message.
940 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
943 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
947 * Hack time. If the first line of the message was blank, with no headers
948 * (this happens occasionally due to bad gatewaying software) cons up
949 * a set of fake headers.
951 * If you modify the fake header template below, be sure you don't
952 * make either From or To address @-less, otherwise the reply_hack
953 * logic will do bad things.
955 if (msgblk.headers == (char *)NULL)
957 snprintf(buf, sizeof(buf),
958 "From: FETCHMAIL-DAEMON\r\n"
960 "Subject: Headerless mail from %s's mailbox on %s\r\n",
961 user, fetchmailhost, ctl->remotename, ctl->server.truename);
962 msgblk.headers = xstrdup(buf);
966 * We can now process message headers before reading the text.
967 * In fact we have to, as this will tell us where to forward to.
970 /* Check for MIME headers indicating possible 8-bit data */
971 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
974 if (ctl->server.sdps && sdps_envfrom)
976 /* We have the real envelope return-path, stored out of band by
977 * SDPS - that's more accurate than any header is going to be.
979 strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
982 #endif /* SDPS_ENABLE */
984 * If there is a Return-Path address on the message, this was
985 * almost certainly the MAIL FROM address given the originating
986 * sendmail. This is the best thing to use for logging the
987 * message origin (it sets up the right behavior for bounces and
988 * mailing lists). Otherwise, fall down to the next available
989 * envelope address (which is the most probable real sender).
990 * *** The order is important! ***
991 * This is especially useful when receiving mailing list
992 * messages in multidrop mode. if a local address doesn't
993 * exist, the bounce message won't be returned blindly to the
994 * author or to the list itself but rather to the list manager
995 * (ex: specified by "Sender:") which is much less annoying. This
996 * is true for most mailing list packages.
998 if( !msgblk.return_path[0] ){
1000 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
1001 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
1002 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
1003 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
1004 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
1005 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
1006 /* multi-line MAIL FROM addresses confuse SMTP terribly */
1007 if (ap && !strchr(ap, '\n')) {
1008 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
1009 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
1013 /* cons up a list of local recipients */
1014 msgblk.recipients = (struct idlist *)NULL;
1015 accept_count = reject_count = 0;
1016 /* is this a multidrop box? */
1020 if (ctl->server.sdps && sdps_envto)
1022 /* We have the real envelope recipient, stored out of band by
1023 * SDPS - that's more accurate than any header is going to be.
1025 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1028 #endif /* SDPS_ENABLE */
1029 if (env_offs > -1) /* We have the actual envelope addressee */
1030 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1031 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1032 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1034 find_server_names(delivered_to, ctl, &msgblk.recipients);
1036 delivered_to = NULL;
1038 else if (received_for)
1040 * We have the Received for addressee.
1041 * It has to be a mailserver address, or we
1042 * wouldn't have got here.
1043 * We use find_server_names() to let local
1044 * hostnames go through.
1046 find_server_names(received_for, ctl, &msgblk.recipients);
1050 * We haven't extracted the envelope address.
1051 * So check all the "Resent-To" header addresses if
1052 * they exist. If and only if they don't, consider
1053 * the "To" addresses.
1055 register struct addrblk *nextptr;
1056 if (resent_to_addrchain) {
1057 /* delete the "To" chain and substitute it
1058 * with the "Resent-To" list
1060 while (to_addrchain) {
1061 nextptr = to_addrchain->next;
1063 to_addrchain = nextptr;
1065 to_addrchain = resent_to_addrchain;
1066 resent_to_addrchain = NULL;
1068 /* now look for remaining adresses */
1069 while (to_addrchain) {
1070 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1071 nextptr = to_addrchain->next;
1073 to_addrchain = nextptr;
1078 no_local_matches = TRUE;
1079 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1080 if (outlevel >= O_DEBUG)
1082 GT_("no local matches, forwarding to %s\n"),
1086 else /* it's a single-drop box, use first localname */
1087 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1091 * Time to either address the message or decide we can't deliver it yet.
1093 if (ctl->errcount > olderrs) /* there were DNS errors above */
1095 if (outlevel >= O_DEBUG)
1097 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1098 free(msgblk.headers);
1099 msgblk.headers = NULL;
1100 free_str_list(&msgblk.recipients);
1101 return(PS_TRANSIENT);
1105 /* set up stuffline() so we can deliver the message body through it */
1106 if ((n = open_sink(ctl, &msgblk,
1107 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1109 free(msgblk.headers);
1110 msgblk.headers = NULL;
1111 free_str_list(&msgblk.recipients);
1118 * Some server/sendmail combinations cause problems when our
1119 * synthetic Received line is before the From header. Cope
1122 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1123 rcv = msgblk.headers;
1124 /* handle ">Received:" lines too */
1125 while (rcv > msgblk.headers && rcv[-1] != '\n')
1127 if (rcv > msgblk.headers)
1132 n = stuffline(ctl, msgblk.headers);
1135 if (!run.invisible && n != -1)
1137 /* utter any per-message Received information we need here */
1138 if (ctl->server.trueaddr) {
1142 e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1143 saddr, sizeof(saddr), NULL, 0,
1146 snprintf(saddr, sizeof(saddr), "(%-.*s)", sizeof(saddr) - 3, gai_strerror(e));
1147 snprintf(buf, sizeof(buf),
1148 "Received: from %s [%s]\r\n",
1149 ctl->server.truename, saddr);
1151 snprintf(buf, sizeof(buf),
1152 "Received: from %s\r\n", ctl->server.truename);
1154 n = stuffline(ctl, buf);
1158 * This header is technically invalid under RFC822.
1159 * POP3, IMAP, etc. are not legal mail-parameter values.
1161 snprintf(buf, sizeof(buf),
1162 "\tby %s with %s (fetchmail-%s",
1166 if (ctl->server.tracepolls)
1168 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1169 " polling %s account %s",
1170 ctl->server.pollname,
1173 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1174 n = stuffline(ctl, buf);
1178 if (good_addresses == 0)
1180 snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1181 rcpt_address (ctl, run.postmaster, 0));
1183 else if (good_addresses == 1)
1185 for (idp = msgblk.recipients; idp; idp = idp->next)
1186 if (idp->val.status.mark == XMIT_ACCEPT)
1187 break; /* only report first address */
1188 snprintf(buf+1, sizeof(buf)-1,
1189 "for <%s>", rcpt_address (ctl, idp->id, 1));
1190 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1192 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1197 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1199 n = stuffline(ctl, buf);
1205 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1209 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1211 free(msgblk.headers);
1212 msgblk.headers = NULL;
1213 free_str_list(&msgblk.recipients);
1216 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
1219 /* write error notifications */
1220 if (no_local_matches || has_nuls || bad_addresses)
1223 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1226 strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1227 if (no_local_matches)
1229 if (reject_count != 1)
1230 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1233 for (idp = msgblk.recipients; idp; idp = idp->next)
1234 if (idp->val.status.mark == XMIT_REJECT)
1236 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1237 GT_("recipient address %s didn't match any local name"), idp->id);
1243 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1244 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1245 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1246 GT_("message has embedded NULs"));
1251 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1252 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1253 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1254 GT_("SMTP listener rejected local recipient addresses: "));
1255 errlen = strlen(errhd);
1256 for (idp = msgblk.recipients; idp; idp = idp->next)
1257 if (idp->val.status.mark == XMIT_RCPTBAD)
1258 errlen += strlen(idp->id) + 2;
1260 errmsg = xmalloc(errlen + 3);
1261 strcpy(errmsg, errhd);
1262 for (idp = msgblk.recipients; idp; idp = idp->next)
1263 if (idp->val.status.mark == XMIT_RCPTBAD)
1265 strcat(errmsg, idp->id);
1267 strcat(errmsg, ", ");
1272 strcat(errmsg, "\r\n");
1274 /* ship out the error line */
1275 stuffline(ctl, errmsg);
1277 if (errmsg != errhd)
1281 /* issue the delimiter line */
1286 stuffline(ctl, buf);
1291 int readbody(int sock, struct query *ctl, flag forward, int len)
1292 /* read and dispose of a message body presented on sock */
1293 /* ctl: query control record */
1294 /* sock: to which the server is connected */
1295 /* len: length of message */
1296 /* forward: TRUE to forward */
1299 unsigned char buf[MSGBUFSIZE+4];
1300 unsigned char *inbufp = buf;
1301 flag issoftline = FALSE;
1304 * Pass through the text lines in the body.
1306 * Yes, this wants to be ||, not &&. The problem is that in the most
1307 * important delimited protocol, POP3, the length is not reliable.
1308 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1309 * So, for delimited protocols we need to ignore the length here and
1310 * instead drop out of the loop with a break statement when we see
1311 * the message delimiter.
1313 while (protocol->delimited || len > 0)
1315 set_timeout(mytimeout);
1316 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1324 /* write the message size dots */
1327 sizeticker += linelen;
1328 while (sizeticker >= SIZETICKER)
1330 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
1335 sizeticker -= SIZETICKER;
1340 /* check for end of message */
1341 if (protocol->delimited && *inbufp == '.')
1343 if (EMPTYLINE(inbufp+1))
1346 msgblk.msglen--; /* subtract the size of the dot escape */
1349 msgblk.msglen += linelen;
1351 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1352 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1353 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1356 * Soft linebreak, but less than 200 bytes left in
1357 * input buffer. Rather than doing a buffer overrun,
1358 * ignore the soft linebreak, NL-terminate data and
1359 * deliver what we have now.
1360 * (Who writes lines longer than 2K anyway?)
1362 *inbufp = '\n'; *(inbufp+1) = '\0';
1367 /* ship out the text line */
1368 if (forward && (!issoftline))
1373 /* guard against very long lines */
1374 buf[MSGBUFSIZE+1] = '\r';
1375 buf[MSGBUFSIZE+2] = '\n';
1376 buf[MSGBUFSIZE+3] = '\0';
1378 n = stuffline(ctl, buf);
1382 report(stdout, GT_("writing message text\n"));
1386 else if (outlevel >= O_VERBOSE && !is_a_file(1) && !run.use_syslog)
1397 void init_transact(const struct method *proto)
1398 /* initialize state for the send and receive functions */
1400 suppress_tags = FALSE;
1402 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1403 protocol = (struct method *)proto;
1407 static void enshroud(char *buf)
1408 /* shroud a password in the given buffer */
1412 if (shroud[0] && (cp = strstr(buf, shroud)))
1416 sp = cp + strlen(shroud);
1424 #if defined(HAVE_STDARG_H)
1425 void gen_send(int sock, const char *fmt, ... )
1427 void gen_send(sock, fmt, va_alist)
1428 int sock; /* socket to which server is connected */
1429 const char *fmt; /* printf-style format */
1432 /* assemble command in printf(3) style and send to the server */
1434 char buf [MSGBUFSIZE+1];
1437 if (protocol->tagged && !suppress_tags)
1438 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1442 #if defined(HAVE_STDARG_H)
1447 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1450 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1451 SockWrite(sock, buf, strlen(buf));
1453 if (outlevel >= O_MONITOR)
1456 buf[strlen(buf)-2] = '\0';
1457 report(stdout, "%s> %s\n", protocol->name, buf);
1461 int gen_recv(sock, buf, size)
1462 /* get one line of input from the server */
1463 int sock; /* socket to which server is connected */
1464 char *buf; /* buffer to receive input */
1465 int size; /* length of buffer */
1467 int oldphase = phase; /* we don't have to be re-entrant */
1469 phase = SERVER_WAIT;
1470 set_timeout(mytimeout);
1471 if (SockRead(sock, buf, size) == -1)
1475 if(is_idletimeout())
1478 return(PS_IDLETIMEOUT);
1486 if (buf[strlen(buf)-1] == '\n')
1487 buf[strlen(buf)-1] = '\0';
1488 if (buf[strlen(buf)-1] == '\r')
1489 buf[strlen(buf)-1] = '\0';
1490 if (outlevel >= O_MONITOR)
1491 report(stdout, "%s< %s\n", protocol->name, buf);
1497 #if defined(HAVE_STDARG_H)
1498 int gen_transact(int sock, const char *fmt, ... )
1500 int gen_transact(int sock, fmt, va_alist)
1501 int sock; /* socket to which server is connected */
1502 const char *fmt; /* printf-style format */
1505 /* assemble command in printf(3) style, send to server, accept a response */
1508 char buf [MSGBUFSIZE+1];
1510 int oldphase = phase; /* we don't have to be re-entrant */
1512 phase = SERVER_WAIT;
1514 if (protocol->tagged && !suppress_tags)
1515 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1519 #if defined(HAVE_STDARG_H)
1524 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1527 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1528 if (SockWrite(sock, buf, strlen(buf)) < strlen(buf)) {
1529 /* short write, bail out */
1533 if (outlevel >= O_MONITOR)
1536 buf[strlen(buf)-2] = '\0';
1537 report(stdout, "%s> %s\n", protocol->name, buf);
1540 /* we presume this does its own response echoing */
1541 ok = (protocol->parse_response)(sock, buf);
1547 /* transact.c ends here */