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