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>
32 #include <sys/socket.h>
38 #include "fetchmail.h"
40 int mytimeout; /* value of nonreponse timeout */
41 int suppress_tags; /* emit tags? */
42 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
47 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
49 static int accept_count, reject_count;
50 static struct method *protocol;
52 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
53 /* add given name to xmit_names if it matches declared localnames */
54 /* name: name to map */
55 /* ctl: list of permissible aliases */
56 /* xmit_names: list of recipient names parsed out */
61 lname = idpair_find(&ctl->localnames, name+off);
62 if (!lname && ctl->wildcard)
65 if (lname != (char *)NULL)
67 if (outlevel >= O_DEBUG)
68 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
69 save_str(xmit_names, lname, XMIT_ACCEPT);
74 static void find_server_names(const char *hdr,
76 struct idlist **xmit_names)
77 /* parse names out of a RFC822 header into an ID list */
78 /* hdr: RFC822 header in question */
79 /* ctl: list of permissible aliases */
80 /* xmit_names: list of recipient names parsed out */
82 if (hdr == (char *)NULL)
88 for (cp = nxtaddr((const unsigned char *)hdr);
95 * Handle empty address from a To: header containing only
102 * If the name of the user begins with a qmail virtual
103 * domain prefix, ignore the prefix. Doing this here
104 * means qvirtual will work either with ordinary name
105 * mapping or with a localdomains option.
107 if (ctl->server.qvirtual)
109 int sl = strlen(ctl->server.qvirtual);
111 if (!strncasecmp((char *)cp, ctl->server.qvirtual, sl))
115 if ((atsign = strchr((char *)cp, '@'))) {
119 * Does a trailing segment of the hostname match something
120 * on the localdomains list? If so, save the whole name
123 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
126 rhs = atsign + (strlen(atsign) - strlen((char *)idp->id));
128 (rhs[-1] == '.' || rhs[-1] == '@') &&
129 strcasecmp(rhs, (char *)idp->id) == 0)
131 if (outlevel >= O_DEBUG)
132 report(stdout, GT_("passed through %s matching %s\n"),
134 save_str(xmit_names, (const char *)cp, XMIT_ACCEPT);
140 /* if we matched a local domain, idp != NULL */
144 * Check to see if the right-hand part is an alias
145 * or MX equivalent of the mailserver. If it's
146 * not, skip this name. If it is, we'll keep
147 * going and try to find a mapping to a client name.
149 if (!is_host_alias(atsign+1, ctl))
151 save_str(xmit_names, cp, XMIT_REJECT);
157 map_name(cp, ctl, xmit_names);
165 * Return zero on a syntactically invalid address, nz on a valid one.
167 * This used to be strchr(a, '.'), but it turns out that lines like this
169 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
170 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
172 * are not uncommon. So now we just check that the following token is
173 * not itself an email address.
175 #define VALID_ADDRESS(a) !strchr(a, '@')
177 static char *parse_received(struct query *ctl, char *bufp)
178 /* try to extract real address from the Received line */
179 /* If a valid Received: line is found, we return the full address in
180 * a buffer which can be parsed from nxtaddr(). This is to ansure that
181 * the local domain part of the address can be passed along in
182 * find_server_names() if it contains one.
183 * Note: We should return a dummy header containing the address
184 * which makes nxtaddr() behave correctly.
187 char *base, *ok = (char *)NULL;
188 static char rbuf[HOSTLEN + USERNAMELEN + 4];
190 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
193 * Try to extract the real envelope addressee. We look here
194 * specifically for the mailserver's Received line.
195 * Note: this will only work for sendmail, or an MTA that
196 * shares sendmail's convention for embedding the envelope
197 * address in the Received line. Sendmail itself only
198 * does this when the mail has a single recipient.
200 if (outlevel >= O_DEBUG)
201 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
203 /* search for whitepace-surrounded "by" followed by valid address */
204 for (base = bufp; ; base = ok + 2)
206 if (!(ok = strstr(base, "by")))
208 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[2]))
214 /* extract space-delimited token after "by" */
215 for (sp = ok + 2; isspace((unsigned char)*sp); sp++)
218 for (; *sp && !isspace((unsigned char)*sp); sp++)
222 /* look for valid address */
223 if (VALID_ADDRESS(rbuf))
226 ok = sp - 1; /* arrange to skip this token */
232 * If it's a DNS name of the mail server, look for the
233 * recipient name after a following "for". Otherwise
236 if (is_host_alias(rbuf, ctl))
238 if (outlevel >= O_DEBUG)
240 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
244 if (outlevel >= O_DEBUG)
246 GT_("line rejected, %s is not an alias of the mailserver\n"),
251 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
252 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
254 if (!(ok = strstr(base, "for")))
256 else if (!isspace((unsigned char)ok[-1]) || !isspace((unsigned char)ok[3]))
262 /* extract space-delimited token after "for" */
263 for (sp = ok + 3; isspace((unsigned char)*sp); sp++)
266 for (; !isspace((unsigned char)*sp); sp++)
270 if (strchr(rbuf, '@'))
273 ok = sp - 1; /* arrange to skip this token */
278 flag want_gt = FALSE;
281 /* char after "for" could be space or a continuation newline */
282 for (sp = ok + 4; isspace((unsigned char)*sp); sp++)
285 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
286 RBUF_WRITE(' '); /* with nxtaddr()... */
292 while (*sp == '@') /* skip routes */
293 while (*sp && *sp++ != ':')
296 && (want_gt ? (*sp != '>') : !isspace((unsigned char)*sp))
298 if (!isspace((unsigned char)*sp))
305 /* uh oh -- whitespace here can't be right! */
311 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
319 if (outlevel >= O_DEBUG)
320 report(stdout, GT_("no Received address found\n"));
325 if (outlevel >= O_DEBUG) {
326 char *lf = rbuf + strlen(rbuf)-1;
328 if (outlevel >= O_DEBUG)
329 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
336 /* shared by readheaders and readbody */
337 static int sizeticker;
339 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
340 || ((s)[0] == '\n' && (s)[1] == '\0'))
342 static int end_of_header (const char *s)
343 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
347 return (s[0] == '\n' && s[1] == '\0');
350 int readheaders(int sock,
355 flag *suppress_readbody)
356 /* read message headers and ship to SMTP or MDA */
357 /* sock: to which the server is connected */
358 /* fetchlen: length of message according to fetch response */
359 /* reallen: length of message according to getsizes */
360 /* ctl: query control record */
361 /* num: index of message */
362 /* suppress_readbody: whether call to readbody() should be supressed */
367 struct addrblk *next;
369 struct addrblk *to_addrchain = NULL;
370 struct addrblk **to_chainptr = &to_addrchain;
371 struct addrblk *resent_to_addrchain = NULL;
372 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
374 char buf[MSGBUFSIZE+1];
375 int from_offs, reply_to_offs, resent_from_offs;
376 int app_from_offs, sender_offs, resent_sender_offs;
378 char *received_for, *rcv, *cp;
379 static char *delivered_to = NULL;
380 int n, oldlen, ch, remaining, skipcount;
383 flag no_local_matches = FALSE;
385 int olderrs, good_addresses, bad_addresses;
386 int retain_mail = 0, refuse_mail = 0;
387 flag already_has_return_path = FALSE;
391 msgblk.return_path[0] = '\0';
392 olderrs = ctl->errcount;
394 /* read message headers */
395 msgblk.reallen = reallen;
398 * We used to free the header block unconditionally at the end of
399 * readheaders, but it turns out that if close_sink() hits an error
400 * condition the code for sending bouncemail will actually look
401 * at the freed storage and coredump...
404 free(msgblk.headers);
405 free_str_list(&msgblk.recipients);
409 /* initially, no message digest */
410 memset(ctl->digest, '\0', sizeof(ctl->digest));
412 msgblk.headers = received_for = delivered_to = NULL;
413 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
414 sender_offs = resent_sender_offs = env_offs = -1;
420 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
423 int overlong = FALSE; /* XXX FIXME: this is unused */
425 line = xmalloc(sizeof(buf));
432 set_timeout(mytimeout);
433 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
436 free(msgblk.headers);
437 msgblk.headers = NULL;
443 * Smash out any NULs, they could wreak havoc later on.
444 * Some network stacks seem to generate these at random,
445 * especially (according to reports) at the beginning of the
446 * first read. NULs are illegal in RFC822 format.
448 for (sp = tp = buf; sp < buf + n; sp++)
461 * Try to gracefully handle the case where the length of a
462 * line exceeds MSGBUFSIZE.
464 if (n && buf[n-1] != '\n')
467 rline = (char *) realloc(line, linelen + 1);
474 memcpy(line + linelen - n, buf, n);
475 line[linelen] = '\0';
476 ch = ' '; /* So the next iteration starts */
480 /* lines may not be properly CRLF terminated; fix this for qmail */
481 /* we don't want to overflow the buffer here */
482 if (ctl->forcecr && buf[n-1]=='\n' && (n==1 || buf[n-2]!='\r'))
485 rline = (char *) realloc(line, linelen + 2);
492 memcpy(line + linelen - n, buf, n - 1);
493 tcp = line + linelen - 1;
502 rline = (char *) realloc(line, linelen + 1);
509 memcpy(line + linelen - n, buf, n + 1);
512 /* check for end of headers */
513 if (end_of_header(line))
515 if (linelen != strlen (line))
518 goto process_headers;
522 * Check for end of message immediately. If one of your folders
523 * has been mangled, the delimiter may occur directly after the
526 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
528 if (outlevel > O_SILENT)
530 GT_("message delimiter found while scanning headers\n"));
531 if (suppress_readbody)
532 *suppress_readbody = TRUE;
533 if (linelen != strlen (line))
536 goto process_headers;
540 * At least one brain-dead website (netmind.com) is known to
541 * send out robotmail that's missing the RFC822 delimiter blank
542 * line before the body! Without this check fetchmail segfaults.
543 * With it, we treat such messages as spam and refuse them.
545 if (!refuse_mail && !isspace((unsigned char)line[0]) && !strchr(line, ':'))
547 if (linelen != strlen (line))
549 if (outlevel > O_SILENT)
551 GT_("incorrect header line found while scanning headers\n"));
552 if (outlevel >= O_VERBOSE)
553 report (stdout, GT_("line: %s"), line);
557 /* check for RFC822 continuations */
558 set_timeout(mytimeout);
562 (ch == ' ' || ch == '\t'); /* continuation to next line? */
564 /* write the message size dots */
565 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
567 sizeticker += linelen;
568 while (sizeticker >= SIZETICKER)
570 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
575 sizeticker -= SIZETICKER;
579 * Decode MIME encoded headers. We MUST do this before
580 * looking at the Content-Type / Content-Transfer-Encoding
581 * headers (RFC 2046).
583 if ( ctl->mimedecode )
587 /* the line is now shorter. So we retrace back till we find our terminating
588 * combination \n\0, we move backwards to make sure that we don't catch som
589 * \n\0 stored in the decoded part of the message */
590 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
591 if(tcp > line) linelen = tcp - line;
595 /* skip processing if we are going to retain or refuse this mail */
596 if (retain_mail || refuse_mail)
602 /* we see an ordinary (non-header, non-message-delimiter line */
603 if (linelen != strlen (line))
607 * The University of Washington IMAP server (the reference
608 * implementation of IMAP4 written by Mark Crispin) relies
609 * on being able to keep base-UID information in a special
610 * message at the head of the mailbox. This message should
611 * neither be deleted nor forwarded.
615 * We disable this check under POP2 because there's no way to
616 * prevent deletion of the message. So at least we ought to
617 * forward it to the user so he or she will have some clue
618 * that things have gone awry.
620 if (servport("pop2") != servport(protocol->service))
621 #endif /* POP2_ENABLE */
622 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
629 * This code prevents fetchmail from becoming an accessory after
630 * the fact to upstream sendmails with the `E' option on. It also
631 * copes with certain brain-dead POP servers (like NT's) that pass
632 * through Unix from_ lines.
634 * Either of these bugs can result in a non-RFC822 line at the
635 * beginning of the headers. If fetchmail just passes it
636 * through, the client listener may think the message has *no*
637 * headers (since the first) line it sees doesn't look
638 * RFC822-conformant) and fake up a set.
640 * What the user would see in this case is bogus (synthesized)
641 * headers, followed by a blank line, followed by the >From,
642 * followed by the real headers, followed by a blank line,
645 * We forestall this lossage by tossing anything that looks
646 * like an escaped or passed-through From_ line in headers.
647 * These aren't RFC822 so our conscience is clear...
649 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
656 * We remove all Delivered-To: headers.
658 * This is to avoid false mail loops messages when delivering
659 * local messages to and from a Postfix/qmail mailserver.
661 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
671 * If we see a Status line, it may have been inserted by an MUA
672 * on the mail host, or it may have been inserted by the server
673 * program after the headers in the transaction stream. This
674 * can actually hose some new-mail notifiers such as xbuffy,
675 * which assumes any Status line came from a *local* MDA and
676 * therefore indicates that the message has been seen.
678 * Some buggy POP servers (including at least the 3.3(20)
679 * version of the one distributed with IMAP) insert empty
680 * Status lines in the transaction stream; we'll chuck those
681 * unconditionally. Nonempty ones get chucked if the user
682 * turns on the dropstatus flag.
687 if (!strncasecmp(line, "Status:", 7))
689 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
694 while (*cp && isspace((unsigned char)*cp)) cp++;
695 if (!*cp || ctl->dropstatus)
704 line = reply_hack(line, ctl->server.truename, &linelen);
707 * OK, this is messy. If we're forwarding by SMTP, it's the
708 * SMTP-receiver's job (according to RFC821, page 22, section
709 * 4.1.1) to generate a Return-Path line on final delivery.
710 * The trouble is, we've already got one because the
711 * mailserver's SMTP thought *it* was responsible for final
714 * Stash away the contents of Return-Path (as modified by reply_hack)
715 * for use in generating MAIL FROM later on, then prevent the header
716 * from being saved with the others. In effect, we strip it off here.
718 * If the SMTP server conforms to the standards, and fetchmail gets the
719 * envelope sender from the Return-Path, the new Return-Path should be
720 * exactly the same as the original one.
722 * We do *not* want to ignore empty Return-Path headers. These should
723 * be passed through as a way of indicating that a message should
724 * not trigger bounces if delivery fails. What we *do* need to do is
725 * make sure we never try to rewrite such a blank Return-Path. We
726 * handle this with a check for <> in the rewrite logic above.
728 * Also, if an email has multiple Return-Path: headers, we only
729 * read the first occurance, as some spam email has more than one
733 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
735 already_has_return_path = TRUE;
736 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
738 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
739 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
749 msgblk.headers = xmalloc(oldlen + 1);
750 (void) memcpy(msgblk.headers, line, linelen);
751 msgblk.headers[oldlen] = '\0';
753 line = msgblk.headers;
760 newlen = oldlen + linelen;
761 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
762 if (newhdrs == NULL) {
766 msgblk.headers = newhdrs;
767 memcpy(msgblk.headers + oldlen, line, linelen);
768 msgblk.headers[newlen] = '\0';
770 line = msgblk.headers + oldlen;
774 /* find offsets of various special headers */
775 if (!strncasecmp("From:", line, 5))
776 from_offs = (line - msgblk.headers);
777 else if (!strncasecmp("Reply-To:", line, 9))
778 reply_to_offs = (line - msgblk.headers);
779 else if (!strncasecmp("Resent-From:", line, 12))
780 resent_from_offs = (line - msgblk.headers);
781 else if (!strncasecmp("Apparently-From:", line, 16))
782 app_from_offs = (line - msgblk.headers);
784 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
786 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
787 * that Sender: *doesn't* have to be a working email address.
789 * The definition of the Sender header in RFC822 says, in
790 * part, "The Sender mailbox specification includes a word
791 * sequence which must correspond to a specific agent (i.e., a
792 * human user or a computer program) rather than a standard
793 * address." That implies that the contents of the Sender
794 * field don't need to be a legal email address at all So
795 * ignore any Sender or Resent-Sender lines unless they
798 * (RFC2822 says the contents of Sender must be a valid mailbox
799 * address, which is also what RFC822 4.4.4 implies.)
801 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
802 sender_offs = (line - msgblk.headers);
803 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
804 resent_sender_offs = (line - msgblk.headers);
807 else if (!strncasecmp("Message-Id:", line, 11))
809 if (ctl->server.uidl)
813 line[IDLEN+12] = 0; /* prevent stack overflow */
814 sscanf(line+12, "%s", id);
815 if (!str_find( &ctl->newsaved, num))
817 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
818 new->val.status.num = num;
822 #endif /* __UNUSED__ */
824 /* if multidrop is on, gather addressee headers */
827 if (!strncasecmp("To:", line, 3)
828 || !strncasecmp("Cc:", line, 3)
829 || !strncasecmp("Bcc:", line, 4)
830 || !strncasecmp("Apparently-To:", line, 14))
832 *to_chainptr = xmalloc(sizeof(struct addrblk));
833 (*to_chainptr)->offset = (line - msgblk.headers);
834 to_chainptr = &(*to_chainptr)->next;
838 else if (!strncasecmp("Resent-To:", line, 10)
839 || !strncasecmp("Resent-Cc:", line, 10)
840 || !strncasecmp("Resent-Bcc:", line, 11))
842 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
843 (*resent_to_chainptr)->offset = (line - msgblk.headers);
844 resent_to_chainptr = &(*resent_to_chainptr)->next;
845 *resent_to_chainptr = NULL;
848 else if (ctl->server.envelope != STRING_DISABLED)
850 if (ctl->server.envelope
851 && strcasecmp(ctl->server.envelope, "Received"))
853 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
855 strlen(ctl->server.envelope)))
857 if (skipcount++ < ctl->server.envskip)
859 env_offs = (line - msgblk.headers);
862 else if (!received_for && !strncasecmp("Received:", line, 9))
864 if (skipcount++ < ctl->server.envskip)
866 received_for = parse_received(ctl, line);
876 free(msgblk.headers);
877 msgblk.headers = NULL;
883 * This is the duplicate-message killer code.
885 * When mail delivered to a multidrop mailbox on the server is
886 * addressed to multiple people on the client machine, there will
887 * be one copy left in the box for each recipient. This is not a
888 * problem if we have the actual recipient address to dispatch on
889 * (e.g. because we've mined it out of sendmail trace headers, or
890 * a qmail Delivered-To line, or a declared sender envelope line).
892 * But if we're mining addressees out of the To/Cc/Bcc fields, and
893 * if the mail is addressed to N people, each recipient will
894 * get N copies. This is bad when N > 1.
896 * Foil this by suppressing all but one copy of a message with a
897 * given set of headers.
899 * Note: This implementation only catches runs of successive
900 * messages with the same ID, but that should be good
901 * enough. A more general implementation would have to store
902 * ever-growing lists of seen message-IDs; in a long-running
903 * daemon this would turn into a memory leak even if the
904 * implementation were perfect.
906 * Don't mess with this code casually. It would be way too easy
907 * to break it in a way that blackholed mail. Better to pass
908 * the occasional duplicate than to do that...
915 MD5Update(&context, msgblk.headers, strlen(msgblk.headers));
916 MD5Final(ctl->digest, &context);
918 if (!received_for && env_offs == -1 && !delivered_to)
921 * Hmmm...can MD5 ever yield all zeroes as a hash value?
922 * If so there is a one in 18-quadrillion chance this
923 * code will incorrectly nuke the first message.
925 if (!memcmp(ctl->lastdigest, ctl->digest, DIGESTLEN))
928 memcpy(ctl->lastdigest, ctl->digest, DIGESTLEN);
932 * Hack time. If the first line of the message was blank, with no headers
933 * (this happens occasionally due to bad gatewaying software) cons up
934 * a set of fake headers.
936 * If you modify the fake header template below, be sure you don't
937 * make either From or To address @-less, otherwise the reply_hack
938 * logic will do bad things.
940 if (msgblk.headers == (char *)NULL)
942 snprintf(buf, sizeof(buf),
943 "From: FETCHMAIL-DAEMON\r\n"
945 "Subject: Headerless mail from %s's mailbox on %s\r\n",
946 user, fetchmailhost, ctl->remotename, ctl->server.truename);
947 msgblk.headers = xstrdup(buf);
951 * We can now process message headers before reading the text.
952 * In fact we have to, as this will tell us where to forward to.
955 /* Check for MIME headers indicating possible 8-bit data */
956 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
959 if (ctl->server.sdps && sdps_envfrom)
961 /* We have the real envelope return-path, stored out of band by
962 * SDPS - that's more accurate than any header is going to be.
964 strlcpy(msgblk.return_path, sdps_envfrom, sizeof(msgblk.return_path));
967 #endif /* SDPS_ENABLE */
969 * If there is a Return-Path address on the message, this was
970 * almost certainly the MAIL FROM address given the originating
971 * sendmail. This is the best thing to use for logging the
972 * message origin (it sets up the right behavior for bounces and
973 * mailing lists). Otherwise, fall down to the next available
974 * envelope address (which is the most probable real sender).
975 * *** The order is important! ***
976 * This is especially useful when receiving mailing list
977 * messages in multidrop mode. if a local address doesn't
978 * exist, the bounce message won't be returned blindly to the
979 * author or to the list itself but rather to the list manager
980 * (ex: specified by "Sender:") which is much less annoying. This
981 * is true for most mailing list packages.
983 if( !msgblk.return_path[0] ){
985 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
986 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
987 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
988 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
989 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
990 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs))) {}
991 /* multi-line MAIL FROM addresses confuse SMTP terribly */
992 if (ap && !strchr(ap, '\n')) {
993 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
994 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
998 /* cons up a list of local recipients */
999 msgblk.recipients = (struct idlist *)NULL;
1000 accept_count = reject_count = 0;
1001 /* is this a multidrop box? */
1005 if (ctl->server.sdps && sdps_envto)
1007 /* We have the real envelope recipient, stored out of band by
1008 * SDPS - that's more accurate than any header is going to be.
1010 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1013 #endif /* SDPS_ENABLE */
1014 if (env_offs > -1) /* We have the actual envelope addressee */
1015 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1016 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1017 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1019 find_server_names(delivered_to, ctl, &msgblk.recipients);
1021 delivered_to = NULL;
1023 else if (received_for)
1025 * We have the Received for addressee.
1026 * It has to be a mailserver address, or we
1027 * wouldn't have got here.
1028 * We use find_server_names() to let local
1029 * hostnames go through.
1031 find_server_names(received_for, ctl, &msgblk.recipients);
1035 * We haven't extracted the envelope address.
1036 * So check all the "Resent-To" header addresses if
1037 * they exist. If and only if they don't, consider
1038 * the "To" addresses.
1040 register struct addrblk *nextptr;
1041 if (resent_to_addrchain) {
1042 /* delete the "To" chain and substitute it
1043 * with the "Resent-To" list
1045 while (to_addrchain) {
1046 nextptr = to_addrchain->next;
1048 to_addrchain = nextptr;
1050 to_addrchain = resent_to_addrchain;
1051 resent_to_addrchain = NULL;
1053 /* now look for remaining adresses */
1054 while (to_addrchain) {
1055 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1056 nextptr = to_addrchain->next;
1058 to_addrchain = nextptr;
1063 no_local_matches = TRUE;
1064 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1065 if (outlevel >= O_DEBUG)
1067 GT_("no local matches, forwarding to %s\n"),
1071 else /* it's a single-drop box, use first localname */
1072 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1076 * Time to either address the message or decide we can't deliver it yet.
1078 if (ctl->errcount > olderrs) /* there were DNS errors above */
1080 if (outlevel >= O_DEBUG)
1082 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1083 free(msgblk.headers);
1084 msgblk.headers = NULL;
1085 free_str_list(&msgblk.recipients);
1086 return(PS_TRANSIENT);
1090 /* set up stuffline() so we can deliver the message body through it */
1091 if ((n = open_sink(ctl, &msgblk,
1092 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1094 free(msgblk.headers);
1095 msgblk.headers = NULL;
1096 free_str_list(&msgblk.recipients);
1103 * Some server/sendmail combinations cause problems when our
1104 * synthetic Received line is before the From header. Cope
1107 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1108 rcv = msgblk.headers;
1109 /* handle ">Received:" lines too */
1110 while (rcv > msgblk.headers && rcv[-1] != '\n')
1112 if (rcv > msgblk.headers)
1117 n = stuffline(ctl, msgblk.headers);
1120 if (!run.invisible && n != -1)
1122 /* utter any per-message Received information we need here */
1123 if (ctl->server.trueaddr) {
1127 e = getnameinfo(ctl->server.trueaddr, ctl->server.trueaddr_len,
1128 saddr, sizeof(saddr), NULL, 0,
1131 snprintf(saddr, sizeof(saddr), "(%-.*s)", sizeof(saddr) - 3, gai_strerror(e));
1132 snprintf(buf, sizeof(buf),
1133 "Received: from %s [%s]\r\n",
1134 ctl->server.truename, saddr);
1136 snprintf(buf, sizeof(buf),
1137 "Received: from %s\r\n", ctl->server.truename);
1139 n = stuffline(ctl, buf);
1143 * This header is technically invalid under RFC822.
1144 * POP3, IMAP, etc. are not legal mail-parameter values.
1146 snprintf(buf, sizeof(buf),
1147 "\tby %s with %s (fetchmail-%s",
1151 if (ctl->server.tracepolls)
1153 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1154 " polling %s account %s",
1155 ctl->server.pollname,
1158 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1159 n = stuffline(ctl, buf);
1163 if (good_addresses == 0)
1165 snprintf(buf+1, sizeof(buf)-1, "for <%s> (by default); ",
1166 rcpt_address (ctl, run.postmaster, 0));
1168 else if (good_addresses == 1)
1170 for (idp = msgblk.recipients; idp; idp = idp->next)
1171 if (idp->val.status.mark == XMIT_ACCEPT)
1172 break; /* only report first address */
1173 snprintf(buf+1, sizeof(buf)-1,
1174 "for <%s>", rcpt_address (ctl, idp->id, 1));
1175 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf)-1,
1177 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1182 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1184 n = stuffline(ctl, buf);
1190 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1194 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1196 free(msgblk.headers);
1197 msgblk.headers = NULL;
1198 free_str_list(&msgblk.recipients);
1201 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(1) && !run.use_syslog)
1204 /* write error notifications */
1205 if (no_local_matches || has_nuls || bad_addresses)
1208 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1211 strlcpy(errhd, "X-Fetchmail-Warning: ", sizeof(errhd));
1212 if (no_local_matches)
1214 if (reject_count != 1)
1215 strlcat(errhd, GT_("no recipient addresses matched declared local names"), sizeof(errhd));
1218 for (idp = msgblk.recipients; idp; idp = idp->next)
1219 if (idp->val.status.mark == XMIT_REJECT)
1221 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1222 GT_("recipient address %s didn't match any local name"), idp->id);
1228 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1229 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1230 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1231 GT_("message has embedded NULs"));
1236 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1237 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1238 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1239 GT_("SMTP listener rejected local recipient addresses: "));
1240 errlen = strlen(errhd);
1241 for (idp = msgblk.recipients; idp; idp = idp->next)
1242 if (idp->val.status.mark == XMIT_RCPTBAD)
1243 errlen += strlen(idp->id) + 2;
1245 errmsg = xmalloc(errlen + 3);
1246 strcpy(errmsg, errhd);
1247 for (idp = msgblk.recipients; idp; idp = idp->next)
1248 if (idp->val.status.mark == XMIT_RCPTBAD)
1250 strcat(errmsg, idp->id);
1252 strcat(errmsg, ", ");
1257 strcat(errmsg, "\r\n");
1259 /* ship out the error line */
1260 stuffline(ctl, errmsg);
1262 if (errmsg != errhd)
1266 /* issue the delimiter line */
1271 stuffline(ctl, buf);
1276 int readbody(int sock, struct query *ctl, flag forward, int len)
1277 /* read and dispose of a message body presented on sock */
1278 /* ctl: query control record */
1279 /* sock: to which the server is connected */
1280 /* len: length of message */
1281 /* forward: TRUE to forward */
1284 unsigned char buf[MSGBUFSIZE+4];
1285 unsigned char *inbufp = buf;
1286 flag issoftline = FALSE;
1289 * Pass through the text lines in the body.
1291 * Yes, this wants to be ||, not &&. The problem is that in the most
1292 * important delimited protocol, POP3, the length is not reliable.
1293 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1294 * So, for delimited protocols we need to ignore the length here and
1295 * instead drop out of the loop with a break statement when we see
1296 * the message delimiter.
1298 while (protocol->delimited || len > 0)
1300 set_timeout(mytimeout);
1301 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1309 /* write the message size dots */
1312 sizeticker += linelen;
1313 while (sizeticker >= SIZETICKER)
1315 if (outlevel > O_SILENT && run.showdots && !run.use_syslog)
1320 sizeticker -= SIZETICKER;
1325 /* check for end of message */
1326 if (protocol->delimited && *inbufp == '.')
1328 if (EMPTYLINE(inbufp+1))
1331 msgblk.msglen--; /* subtract the size of the dot escape */
1334 msgblk.msglen += linelen;
1336 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1337 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1338 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1341 * Soft linebreak, but less than 200 bytes left in
1342 * input buffer. Rather than doing a buffer overrun,
1343 * ignore the soft linebreak, NL-terminate data and
1344 * deliver what we have now.
1345 * (Who writes lines longer than 2K anyway?)
1347 *inbufp = '\n'; *(inbufp+1) = '\0';
1352 /* ship out the text line */
1353 if (forward && (!issoftline))
1358 /* guard against very long lines */
1359 buf[MSGBUFSIZE+1] = '\r';
1360 buf[MSGBUFSIZE+2] = '\n';
1361 buf[MSGBUFSIZE+3] = '\0';
1363 n = stuffline(ctl, buf);
1367 report(stdout, GT_("writing message text\n"));
1371 else if (outlevel >= O_VERBOSE && !isafile(1) && !run.use_syslog)
1382 void init_transact(const struct method *proto)
1383 /* initialize state for the send and receive functions */
1386 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1387 protocol = (struct method *)proto;
1390 static void enshroud(char *buf)
1391 /* shroud a password in the given buffer */
1395 if (shroud[0] && (cp = strstr(buf, shroud)))
1399 sp = cp + strlen(shroud);
1407 #if defined(HAVE_STDARG_H)
1408 void gen_send(int sock, const char *fmt, ... )
1410 void gen_send(sock, fmt, va_alist)
1411 int sock; /* socket to which server is connected */
1412 const char *fmt; /* printf-style format */
1415 /* assemble command in printf(3) style and send to the server */
1417 char buf [MSGBUFSIZE+1];
1420 if (protocol->tagged && !suppress_tags)
1421 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1425 #if defined(HAVE_STDARG_H)
1430 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1433 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1434 SockWrite(sock, buf, strlen(buf));
1436 if (outlevel >= O_MONITOR)
1439 buf[strlen(buf)-2] = '\0';
1440 report(stdout, "%s> %s\n", protocol->name, buf);
1444 int gen_recv(sock, buf, size)
1445 /* get one line of input from the server */
1446 int sock; /* socket to which server is connected */
1447 char *buf; /* buffer to receive input */
1448 int size; /* length of buffer */
1450 int oldphase = phase; /* we don't have to be re-entrant */
1452 phase = SERVER_WAIT;
1453 set_timeout(mytimeout);
1454 if (SockRead(sock, buf, size) == -1)
1461 return(PS_IDLETIMEOUT);
1469 if (buf[strlen(buf)-1] == '\n')
1470 buf[strlen(buf)-1] = '\0';
1471 if (buf[strlen(buf)-1] == '\r')
1472 buf[strlen(buf)-1] = '\0';
1473 if (outlevel >= O_MONITOR)
1474 report(stdout, "%s< %s\n", protocol->name, buf);
1480 #if defined(HAVE_STDARG_H)
1481 int gen_transact(int sock, const char *fmt, ... )
1483 int gen_transact(int sock, fmt, va_alist)
1484 int sock; /* socket to which server is connected */
1485 const char *fmt; /* printf-style format */
1488 /* assemble command in printf(3) style, send to server, accept a response */
1491 char buf [MSGBUFSIZE+1];
1493 int oldphase = phase; /* we don't have to be re-entrant */
1495 phase = SERVER_WAIT;
1497 if (protocol->tagged && !suppress_tags)
1498 snprintf(buf, sizeof(buf) - 2, "%s ", GENSYM);
1502 #if defined(HAVE_STDARG_H)
1507 vsnprintf(buf + strlen(buf), sizeof(buf)-2-strlen(buf), fmt, ap);
1510 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1511 if (SockWrite(sock, buf, strlen(buf)) < strlen(buf)) {
1512 /* short write, bail out */
1516 if (outlevel >= O_MONITOR)
1519 buf[strlen(buf)-2] = '\0';
1520 report(stdout, "%s> %s\n", protocol->name, buf);
1523 /* we presume this does its own response echoing */
1524 ok = (protocol->parse_response)(sock, buf);
1530 /* transact.c ends here */