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>
35 #include "fetchmail.h"
37 #ifndef strstr /* glibc-2.1 declares this as a macro */
38 extern char *strstr(); /* needed on sysV68 R3V7.1. */
41 int mytimeout; /* value of nonreponse timeout */
42 int suppress_tags; /* emit tags? */
43 char shroud[PASSWORDLEN*2+3]; /* string to shroud in debug output */
48 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
50 static int accept_count, reject_count;
51 static struct method *protocol;
53 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
54 /* add given name to xmit_names if it matches declared localnames */
55 /* name: name to map */
56 /* ctl: list of permissible aliases */
57 /* xmit_names: list of recipient names parsed out */
62 lname = idpair_find(&ctl->localnames, name+off);
63 if (!lname && ctl->wildcard)
66 if (lname != (char *)NULL)
68 if (outlevel >= O_DEBUG)
69 report(stdout, GT_("mapped %s to local %s\n"), name, lname);
70 save_str(xmit_names, lname, XMIT_ACCEPT);
75 static void find_server_names(const char *hdr,
77 struct idlist **xmit_names)
78 /* parse names out of a RFC822 header into an ID list */
79 /* hdr: RFC822 header in question */
80 /* ctl: list of permissible aliases */
81 /* xmit_names: list of recipient names parsed out */
83 if (hdr == (char *)NULL)
89 for (cp = nxtaddr(hdr);
96 * Handle empty address from a To: header containing only
103 * If the name of the user begins with a qmail virtual
104 * domain prefix, ignore the prefix. Doing this here
105 * means qvirtual will work either with ordinary name
106 * mapping or with a localdomains option.
108 if (ctl->server.qvirtual)
110 int sl = strlen(ctl->server.qvirtual);
112 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
116 if ((atsign = strchr(cp, '@'))) {
120 * Does a trailing segment of the hostname match something
121 * on the localdomains list? If so, save the whole name
124 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
127 rhs = atsign + (strlen(atsign) - strlen(idp->id));
129 (rhs[-1] == '.' || rhs[-1] == '@') &&
130 strcasecmp(rhs, idp->id) == 0)
132 if (outlevel >= O_DEBUG)
133 report(stdout, GT_("passed through %s matching %s\n"),
135 save_str(xmit_names, cp, XMIT_ACCEPT);
141 /* if we matched a local domain, idp != NULL */
145 * Check to see if the right-hand part is an alias
146 * or MX equivalent of the mailserver. If it's
147 * not, skip this name. If it is, we'll keep
148 * going and try to find a mapping to a client name.
150 if (!is_host_alias(atsign+1, ctl))
152 save_str(xmit_names, cp, XMIT_REJECT);
158 map_name(cp, ctl, xmit_names);
166 * Return zero on a syntactically invalid address, nz on a valid one.
168 * This used to be strchr(a, '.'), but it turns out that lines like this
170 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
171 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
173 * are not uncommon. So now we just check that the following token is
174 * not itself an email address.
176 #define VALID_ADDRESS(a) !strchr(a, '@')
178 static char *parse_received(struct query *ctl, char *bufp)
179 /* try to extract real address from the Received line */
180 /* If a valid Received: line is found, we return the full address in
181 * a buffer which can be parsed from nxtaddr(). This is to ansure that
182 * the local domain part of the address can be passed along in
183 * find_server_names() if it contains one.
184 * Note: We should return a dummy header containing the address
185 * which makes nxtaddr() behave correctly.
188 char *base, *ok = (char *)NULL;
189 static char rbuf[HOSTLEN + USERNAMELEN + 4];
191 #define RBUF_WRITE(value) if (tp < rbuf+sizeof(rbuf)-1) *tp++=value
194 * Try to extract the real envelope addressee. We look here
195 * specifically for the mailserver's Received line.
196 * Note: this will only work for sendmail, or an MTA that
197 * shares sendmail's convention for embedding the envelope
198 * address in the Received line. Sendmail itself only
199 * does this when the mail has a single recipient.
201 if (outlevel >= O_DEBUG)
202 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
204 /* search for whitepace-surrounded "by" followed by valid address */
205 for (base = bufp; ; base = ok + 2)
207 if (!(ok = strstr(base, "by")))
209 else if (!isspace(ok[-1]) || !isspace(ok[2]))
215 /* extract space-delimited token after "by" */
216 for (sp = ok + 2; isspace(*sp); sp++)
219 for (; !isspace(*sp); sp++)
223 /* look for valid address */
224 if (VALID_ADDRESS(rbuf))
227 ok = sp - 1; /* arrange to skip this token */
233 * If it's a DNS name of the mail server, look for the
234 * recipient name after a following "for". Otherwise
237 if (is_host_alias(rbuf, ctl))
239 if (outlevel >= O_DEBUG)
241 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
245 if (outlevel >= O_DEBUG)
247 GT_("line rejected, %s is not an alias of the mailserver\n"),
252 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
253 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
255 if (!(ok = strstr(base, "for")))
257 else if (!isspace(ok[-1]) || !isspace(ok[3]))
263 /* extract space-delimited token after "for" */
264 for (sp = ok + 3; isspace(*sp); sp++)
267 for (; !isspace(*sp); sp++)
271 if (strchr(rbuf, '@'))
274 ok = sp - 1; /* arrange to skip this token */
279 flag want_gt = FALSE;
282 /* char after "for" could be space or a continuation newline */
283 for (sp = ok + 4; isspace(*sp); sp++)
286 RBUF_WRITE(':'); /* Here is the hack. This is to be friends */
287 RBUF_WRITE(' '); /* with nxtaddr()... */
293 while (*sp == '@') /* skip routes */
294 while (*sp && *sp++ != ':')
297 && (want_gt ? (*sp != '>') : !isspace(*sp))
306 /* uh oh -- whitespace here can't be right! */
312 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
320 if (outlevel >= O_DEBUG)
321 report(stdout, GT_("no Received address found\n"));
326 if (outlevel >= O_DEBUG) {
327 char *lf = rbuf + strlen(rbuf)-1;
329 if (outlevel >= O_DEBUG)
330 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
337 /* shared by readheaders and readbody */
338 static int sizeticker;
340 #define EMPTYLINE(s) (((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0') \
341 || ((s)[0] == '\n' && (s)[1] == '\0'))
343 static int end_of_header (const char *s)
344 /* accept "\r*\n" as EOH in order to be bulletproof against broken survers */
348 return (s[0] == '\n' && s[1] == '\0');
351 int readheaders(int sock,
356 flag *suppress_readbody)
357 /* read message headers and ship to SMTP or MDA */
358 /* sock: to which the server is connected */
359 /* fetchlen: length of message according to fetch response */
360 /* reallen: length of message according to getsizes */
361 /* ctl: query control record */
362 /* num: index of message */
363 /* suppress_readbody: whether call to readbody() should be supressed */
368 struct addrblk *next;
370 struct addrblk *to_addrchain = NULL;
371 struct addrblk **to_chainptr = &to_addrchain;
372 struct addrblk *resent_to_addrchain = NULL;
373 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
375 char buf[MSGBUFSIZE+1];
376 int from_offs, reply_to_offs, resent_from_offs;
377 int app_from_offs, sender_offs, resent_sender_offs;
379 char *received_for, *rcv, *cp;
380 static char *delivered_to = NULL;
381 int n, linelen, 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 ID */
414 msgblk.headers = received_for = delivered_to = NULL;
415 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
416 sender_offs = resent_sender_offs = env_offs = -1;
422 for (remaining = fetchlen; remaining > 0 || protocol->delimited; )
425 int overlong = FALSE;
427 line = xmalloc(sizeof(buf));
431 set_timeout(mytimeout);
432 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
435 free(msgblk.headers);
436 msgblk.headers = NULL;
446 * Try to gracefully handle the case, where the length of a
447 * line exceeds MSGBUFSIZE.
449 if ( n && buf[n-1] != '\n' ) {
451 rline = (char *) realloc(line, linelen + 1);
458 memcpy(line + linelen - n, buf, n);
459 line[linelen] = '\0';
460 ch = ' '; /* So the next iteration starts */
465 /* lines may not be properly CRLF terminated; fix this for qmail */
466 /* we don't want to overflow the buffer here */
467 if (ctl->forcecr && buf[n-1] == '\n' && (n == 1 || buf[n-2] != '\r'))
470 rline = (char *) realloc(line, linelen + 2);
477 memcpy(line + linelen - n, buf, n - 1);
478 tcp = line + linelen - 1;
487 rline = (char *) realloc(line, linelen + 1);
494 memcpy(line + linelen - n, buf, n + 1);
497 /* check for end of headers */
498 if (end_of_header(line))
500 if (linelen != strlen (line))
503 goto process_headers;
507 * Check for end of message immediately. If one of your folders
508 * has been mangled, the delimiter may occur directly after the
511 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
513 if (outlevel > O_SILENT)
515 GT_("message delimiter found while scanning headers\n"));
516 if (suppress_readbody)
517 *suppress_readbody = TRUE;
518 if (linelen != strlen (line))
521 goto process_headers;
525 * At least one brain-dead website (netmind.com) is known to
526 * send out robotmail that's missing the RFC822 delimiter blank
527 * line before the body! Without this check fetchmail segfaults.
528 * With it, we treat such messages as spam and refuse them.
530 if (!refuse_mail && !isspace(line[0]) && !strchr(line, ':'))
532 if (linelen != strlen (line))
534 if (outlevel > O_SILENT)
536 GT_("incorrect header line found while scanning headers\n"));
537 if (outlevel >= O_VERBOSE)
538 report (stdout, GT_("line: %s"), line);
542 /* check for RFC822 continuations */
543 set_timeout(mytimeout);
547 (ch == ' ' || ch == '\t'); /* continuation to next line? */
549 /* write the message size dots */
550 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
552 sizeticker += linelen;
553 while (sizeticker >= SIZETICKER)
555 if (outlevel > O_SILENT && run.showdots)
560 sizeticker -= SIZETICKER;
564 * Decode MIME encoded headers. We MUST do this before
565 * looking at the Content-Type / Content-Transfer-Encoding
566 * headers (RFC 2046).
568 if ( ctl->mimedecode )
572 /* the line is now shorter. So we retrace back till we find our terminating
573 * combination \n\0, we move backwards to make sure that we don't catch som
574 * \n\0 stored in the decoded part of the message */
575 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
576 if(tcp > line) linelen = tcp - line;
580 /* skip processing if we are going to retain or refuse this mail */
581 if (retain_mail || refuse_mail)
587 /* we see an ordinary (non-header, non-message-delimiter line */
588 if (linelen != strlen (line))
591 /* save the message's ID, we may use it for killing duplicates later */
592 if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
593 ctl->thisid = xstrdup(line);
596 * The University of Washington IMAP server (the reference
597 * implementation of IMAP4 written by Mark Crispin) relies
598 * on being able to keep base-UID information in a special
599 * message at the head of the mailbox. This message should
600 * neither be deleted nor forwarded.
604 * We disable this check under POP2 because there's no way to
605 * prevent deletion of the message. So at least we ought to
606 * forward it to the user so he or she will have some clue
607 * that things have gone awry.
610 if (strncmp(protocol->service, "pop2", 4))
611 #else /* INET6_ENABLE */
612 if (protocol->port != 109)
613 #endif /* INET6_ENABLE */
614 #endif /* POP2_ENABLE */
615 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
622 * This code prevents fetchmail from becoming an accessory after
623 * the fact to upstream sendmails with the `E' option on. It also
624 * copes with certain brain-dead POP servers (like NT's) that pass
625 * through Unix from_ lines.
627 * Either of these bugs can result in a non-RFC822 line at the
628 * beginning of the headers. If fetchmail just passes it
629 * through, the client listener may think the message has *no*
630 * headers (since the first) line it sees doesn't look
631 * RFC822-conformant) and fake up a set.
633 * What the user would see in this case is bogus (synthesized)
634 * headers, followed by a blank line, followed by the >From,
635 * followed by the real headers, followed by a blank line,
638 * We forestall this lossage by tossing anything that looks
639 * like an escaped or passed-through From_ line in headers.
640 * These aren't RFC822 so our conscience is clear...
642 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
649 * We remove all Delivered-To: headers.
651 * This is to avoid false mail loops messages when delivering
652 * local messages to and from a Postfix/qmail mailserver.
654 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
664 * If we see a Status line, it may have been inserted by an MUA
665 * on the mail host, or it may have been inserted by the server
666 * program after the headers in the transaction stream. This
667 * can actually hose some new-mail notifiers such as xbuffy,
668 * which assumes any Status line came from a *local* MDA and
669 * therefore indicates that the message has been seen.
671 * Some buggy POP servers (including at least the 3.3(20)
672 * version of the one distributed with IMAP) insert empty
673 * Status lines in the transaction stream; we'll chuck those
674 * unconditionally. Nonempty ones get chucked if the user
675 * turns on the dropstatus flag.
680 if (!strncasecmp(line, "Status:", 7))
682 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
687 while (*cp && isspace(*cp)) cp++;
688 if (!*cp || ctl->dropstatus)
697 line = reply_hack(line, ctl->server.truename, &linelen);
700 * OK, this is messy. If we're forwarding by SMTP, it's the
701 * SMTP-receiver's job (according to RFC821, page 22, section
702 * 4.1.1) to generate a Return-Path line on final delivery.
703 * The trouble is, we've already got one because the
704 * mailserver's SMTP thought *it* was responsible for final
707 * Stash away the contents of Return-Path (as modified by reply_hack)
708 * for use in generating MAIL FROM later on, then prevent the header
709 * from being saved with the others. In effect, we strip it off here.
711 * If the SMTP server conforms to the standards, and fetchmail gets the
712 * envelope sender from the Return-Path, the new Return-Path should be
713 * exactly the same as the original one.
715 * We do *not* want to ignore empty Return-Path headers. These should
716 * be passed through as a way of indicating that a message should
717 * not trigger bounces if delivery fails. What we *do* need to do is
718 * make sure we never try to rewrite such a blank Return-Path. We
719 * handle this with a check for <> in the rewrite logic above.
721 * Also, if an email has multiple Return-Path: statement, we only
722 * read the first occurance, as some spam email has more than one
726 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
728 already_has_return_path = TRUE;
729 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
731 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
732 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
742 msgblk.headers = xmalloc(oldlen + 1);
743 (void) memcpy(msgblk.headers, line, linelen);
744 msgblk.headers[oldlen] = '\0';
746 line = msgblk.headers;
753 newlen = oldlen + linelen;
754 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
755 if (newhdrs == NULL) {
759 msgblk.headers = newhdrs;
760 memcpy(msgblk.headers + oldlen, line, linelen);
761 msgblk.headers[newlen] = '\0';
763 line = msgblk.headers + oldlen;
767 /* find offsets of various special headers */
768 if (!strncasecmp("From:", line, 5))
769 from_offs = (line - msgblk.headers);
770 else if (!strncasecmp("Reply-To:", line, 9))
771 reply_to_offs = (line - msgblk.headers);
772 else if (!strncasecmp("Resent-From:", line, 12))
773 resent_from_offs = (line - msgblk.headers);
774 else if (!strncasecmp("Apparently-From:", line, 16))
775 app_from_offs = (line - msgblk.headers);
777 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
779 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
780 * that Sender: *doesn't* have to be a working email address.
782 * The definition of the Sender header in RFC822 says, in
783 * part, "The Sender mailbox specification includes a word
784 * sequence which must correspond to a specific agent (i.e., a
785 * human user or a computer program) rather than a standard
786 * address." That implies that the contents of the Sender
787 * field don't need to be a legal email address at all So
788 * ignore any Sender or Resent-Sender lines unless they
791 * (RFC2822 says the contents of Sender must be a valid mailbox
792 * address, which is also what RFC822 4.4.4 implies.)
794 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
795 sender_offs = (line - msgblk.headers);
796 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
797 resent_sender_offs = (line - msgblk.headers);
800 else if (!strncasecmp("Message-Id:", line, 11))
802 if (ctl->server.uidl)
806 line[IDLEN+12] = 0; /* prevent stack overflow */
807 sscanf(line+12, "%s", id);
808 if (!str_find( &ctl->newsaved, num))
810 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
811 new->val.status.num = num;
815 #endif /* __UNUSED__ */
817 /* if multidrop is on, gather addressee headers */
820 if (!strncasecmp("To:", line, 3)
821 || !strncasecmp("Cc:", line, 3)
822 || !strncasecmp("Bcc:", line, 4)
823 || !strncasecmp("Apparently-To:", line, 14))
825 *to_chainptr = xmalloc(sizeof(struct addrblk));
826 (*to_chainptr)->offset = (line - msgblk.headers);
827 to_chainptr = &(*to_chainptr)->next;
831 else if (!strncasecmp("Resent-To:", line, 10)
832 || !strncasecmp("Resent-Cc:", line, 10)
833 || !strncasecmp("Resent-Bcc:", line, 11))
835 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
836 (*resent_to_chainptr)->offset = (line - msgblk.headers);
837 resent_to_chainptr = &(*resent_to_chainptr)->next;
838 *resent_to_chainptr = NULL;
841 else if (ctl->server.envelope != STRING_DISABLED)
843 if (ctl->server.envelope
844 && strcasecmp(ctl->server.envelope, "Received"))
846 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
848 strlen(ctl->server.envelope)))
850 if (skipcount++ < ctl->server.envskip)
852 env_offs = (line - msgblk.headers);
855 else if (!received_for && !strncasecmp("Received:", line, 9))
857 if (skipcount++ < ctl->server.envskip)
859 received_for = parse_received(ctl, line);
869 free(msgblk.headers);
870 msgblk.headers = NULL;
876 * When mail delivered to a multidrop mailbox on the server is
877 * addressed to multiple people on the client machine, there will
878 * be one copy left in the box for each recipient. This is not a
879 * problem if we have the actual recipient address to dispatch on
880 * (e.g. because we've mined it out of sendmail trace headers, or
881 * a qmail Delivered-To line, or a declared sender envelope line).
883 * But if we're mining addressees out of the To/Cc/Bcc fields, and
884 * if the mail is addressed to N people, each recipient will
885 * get N copies. This is bad when N > 1.
887 * Foil this by suppressing all but one copy of a message with
888 * a given Message-ID. The accept_count test ensures that
889 * multiple pieces of email with the same Message-ID, each
890 * with a *single* addressee (the N == 1 case), won't be
893 * Note: This implementation only catches runs of successive
894 * messages with the same ID, but that should be good
895 * enough. A more general implementation would have to store
896 * ever-growing lists of seen message-IDs; in a long-running
897 * daemon this would turn into a memory leak even if the
898 * implementation were perfect.
900 * Don't mess with this code casually. It would be way too easy
901 * to break it in a way that blackholed mail. Better to pass
902 * the occasional duplicate than to do that...
904 if (!received_for && env_offs == -1 && !delivered_to)
906 if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
908 if (accept_count > 1)
915 ctl->lastid = ctl->thisid;
921 * Hack time. If the first line of the message was blank, with no headers
922 * (this happens occasionally due to bad gatewaying software) cons up
923 * a set of fake headers.
925 * If you modify the fake header template below, be sure you don't
926 * make either From or To address @-less, otherwise the reply_hack
927 * logic will do bad things.
929 if (msgblk.headers == (char *)NULL)
932 snprintf(buf, sizeof(buf),
935 #endif /* HAVE_SNPRINTF */
936 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
937 user, fetchmailhost, ctl->remotename, ctl->server.truename);
938 msgblk.headers = xstrdup(buf);
942 * We can now process message headers before reading the text.
943 * In fact we have to, as this will tell us where to forward to.
946 /* Check for MIME headers indicating possible 8-bit data */
947 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
950 if (ctl->server.sdps && sdps_envfrom)
952 /* We have the real envelope return-path, stored out of band by
953 * SDPS - that's more accurate than any header is going to be.
955 strcpy(msgblk.return_path, sdps_envfrom);
958 #endif /* SDPS_ENABLE */
960 * If there is a Return-Path address on the message, this was
961 * almost certainly the MAIL FROM address given the originating
962 * sendmail. This is the best thing to use for logging the
963 * message origin (it sets up the right behavior for bounces and
964 * mailing lists). Otherwise, fall down to the next available
965 * envelope address (which is the most probable real sender).
966 * *** The order is important! ***
967 * This is especially useful when receiving mailing list
968 * messages in multidrop mode. if a local address doesn't
969 * exist, the bounce message won't be returned blindly to the
970 * author or to the list itself but rather to the list manager
971 * (ex: specified by "Sender:") which is much less annoying. This
972 * is true for most mailing list packages.
974 if( !msgblk.return_path[0] ){
976 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
977 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
978 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
979 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
980 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
981 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
982 /* multi-line MAIL FROM addresses confuse SMTP terribly */
983 if (ap && !strchr(ap, '\n')) {
984 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
985 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
989 /* cons up a list of local recipients */
990 msgblk.recipients = (struct idlist *)NULL;
991 accept_count = reject_count = 0;
992 /* is this a multidrop box? */
996 if (ctl->server.sdps && sdps_envto)
998 /* We have the real envelope recipient, stored out of band by
999 * SDPS - that's more accurate than any header is going to be.
1001 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1004 #endif /* SDPS_ENABLE */
1005 if (env_offs > -1) /* We have the actual envelope addressee */
1006 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1007 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1008 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1010 find_server_names(delivered_to, ctl, &msgblk.recipients);
1012 delivered_to = NULL;
1014 else if (received_for)
1016 * We have the Received for addressee.
1017 * It has to be a mailserver address, or we
1018 * wouldn't have got here.
1019 * We use find_server_names() to let local
1020 * hostnames go through.
1022 find_server_names(received_for, ctl, &msgblk.recipients);
1026 * We haven't extracted the envelope address.
1027 * So check all the "Resent-To" header addresses if
1028 * they exist. If and only if they don't, consider
1029 * the "To" addresses.
1031 register struct addrblk *nextptr;
1032 if (resent_to_addrchain) {
1033 /* delete the "To" chain and substitute it
1034 * with the "Resent-To" list
1036 while (to_addrchain) {
1037 nextptr = to_addrchain->next;
1039 to_addrchain = nextptr;
1041 to_addrchain = resent_to_addrchain;
1042 resent_to_addrchain = NULL;
1044 /* now look for remaining adresses */
1045 while (to_addrchain) {
1046 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1047 nextptr = to_addrchain->next;
1049 to_addrchain = nextptr;
1054 no_local_matches = TRUE;
1055 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1056 if (outlevel >= O_DEBUG)
1058 GT_("no local matches, forwarding to %s\n"),
1062 else /* it's a single-drop box, use first localname */
1063 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1067 * Time to either address the message or decide we can't deliver it yet.
1069 if (ctl->errcount > olderrs) /* there were DNS errors above */
1071 if (outlevel >= O_DEBUG)
1073 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1074 free(msgblk.headers);
1075 msgblk.headers = NULL;
1076 free_str_list(&msgblk.recipients);
1077 return(PS_TRANSIENT);
1081 /* set up stuffline() so we can deliver the message body through it */
1082 if ((n = open_sink(ctl, &msgblk,
1083 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1085 free(msgblk.headers);
1086 msgblk.headers = NULL;
1087 free_str_list(&msgblk.recipients);
1094 * Some server/sendmail combinations cause problems when our
1095 * synthetic Received line is before the From header. Cope
1098 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1099 rcv = msgblk.headers;
1100 /* handle ">Received:" lines too */
1101 while (rcv > msgblk.headers && rcv[-1] != '\n')
1103 if (rcv > msgblk.headers)
1108 n = stuffline(ctl, msgblk.headers);
1111 if (!run.invisible && n != -1)
1113 /* utter any per-message Received information we need here */
1114 if (ctl->server.trueaddr) {
1115 #ifdef HAVE_SNPRINTF
1116 snprintf(buf, sizeof(buf),
1119 #endif /* HAVE_SNPRINTF */
1120 "Received: from %s [%u.%u.%u.%u]\r\n",
1121 ctl->server.truename,
1122 (unsigned char)ctl->server.trueaddr[0],
1123 (unsigned char)ctl->server.trueaddr[1],
1124 (unsigned char)ctl->server.trueaddr[2],
1125 (unsigned char)ctl->server.trueaddr[3]);
1127 #ifdef HAVE_SNPRINTF
1128 snprintf(buf, sizeof(buf),
1131 #endif /* HAVE_SNPRINTF */
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 #ifdef HAVE_SNPRINTF
1142 snprintf(buf, sizeof(buf),
1145 #endif /* HAVE_SNPRINTF */
1146 "\tby %s with %s (fetchmail-%s",
1150 if (ctl->tracepolls)
1152 sprintf(buf + strlen(buf), " polling %s account %s",
1153 ctl->server.pollname,
1156 #ifdef HAVE_SNPRINTF
1157 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1159 strcat(buf, ")\r\n");
1160 #endif /* HAVE_SNPRINTF */
1161 n = stuffline(ctl, buf);
1165 if (good_addresses == 0)
1167 #ifdef HAVE_SNPRINTF
1168 snprintf(buf+1, sizeof(buf)-1,
1171 #endif /* HAVE_SNPRINTF */
1172 "for %s (by default); ",
1173 rcpt_address (ctl, run.postmaster, 0));
1175 else if (good_addresses == 1)
1177 for (idp = msgblk.recipients; idp; idp = idp->next)
1178 if (idp->val.status.mark == XMIT_ACCEPT)
1179 break; /* only report first address */
1180 #ifdef HAVE_SNPRINTF
1181 snprintf(buf+1, sizeof(buf)-1,
1184 #endif /* HAVE_SNPRINTF */
1185 "for %s", rcpt_address (ctl, idp->id, 1));
1186 sprintf(buf+strlen(buf), " (%s); ",
1187 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1192 #ifdef HAVE_SNPRINTF
1193 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1196 strcat(buf, rfc822timestamp());
1197 strcat(buf, "\r\n");
1198 #endif /* HAVE_SNPRINTF */
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 && !isafile(2))
1219 /* write error notifications */
1220 if (no_local_matches || has_nuls || bad_addresses)
1223 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1226 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1227 if (no_local_matches)
1229 if (reject_count != 1)
1230 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1233 for (idp = msgblk.recipients; idp; idp = idp->next)
1234 if (idp->val.status.mark == XMIT_REJECT)
1236 #ifdef HAVE_SNPRINTF
1237 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1239 sprintf(errhd+strlen(errhd),
1240 #endif /* HAVE_SNPRINTF */
1241 GT_("recipient address %s didn't match any local name"), idp->id);
1247 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1248 #ifdef HAVE_SNPRINTF
1249 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1250 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1252 strcat(errhd, "; ");
1254 #endif /* HAVE_SNPRINTF */
1255 GT_("message has embedded NULs"));
1260 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1261 #ifdef HAVE_SNPRINTF
1262 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1263 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1265 strcat(errhd, "; ");
1267 #endif /* HAVE_SNPRINTF */
1268 GT_("SMTP listener rejected local recipient addresses: "));
1269 errlen = strlen(errhd);
1270 for (idp = msgblk.recipients; idp; idp = idp->next)
1271 if (idp->val.status.mark == XMIT_RCPTBAD)
1272 errlen += strlen(idp->id) + 2;
1274 xalloca(errmsg, char *, errlen+3);
1275 (void) strcpy(errmsg, errhd);
1276 for (idp = msgblk.recipients; idp; idp = idp->next)
1277 if (idp->val.status.mark == XMIT_RCPTBAD)
1279 strcat(errmsg, idp->id);
1281 strcat(errmsg, ", ");
1286 strcat(errmsg, "\r\n");
1288 /* ship out the error line */
1289 stuffline(ctl, errmsg);
1292 /* issue the delimiter line */
1297 stuffline(ctl, buf);
1302 int readbody(int sock, struct query *ctl, flag forward, int len)
1303 /* read and dispose of a message body presented on sock */
1304 /* ctl: query control record */
1305 /* sock: to which the server is connected */
1306 /* len: length of message */
1307 /* forward: TRUE to forward */
1310 unsigned char buf[MSGBUFSIZE+4];
1311 unsigned char *inbufp = buf;
1312 flag issoftline = FALSE;
1315 * Pass through the text lines in the body.
1317 * Yes, this wants to be ||, not &&. The problem is that in the most
1318 * important delimited protocol, POP3, the length is not reliable.
1319 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1320 * So, for delimited protocols we need to ignore the length here and
1321 * instead drop out of the loop with a break statement when we see
1322 * the message delimiter.
1324 while (protocol->delimited || len > 0)
1326 set_timeout(mytimeout);
1327 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1335 /* write the message size dots */
1338 sizeticker += linelen;
1339 while (sizeticker >= SIZETICKER)
1341 if (outlevel > O_SILENT && run.showdots)
1346 sizeticker -= SIZETICKER;
1351 /* check for end of message */
1352 if (protocol->delimited && *inbufp == '.')
1354 if (EMPTYLINE(inbufp+1))
1357 msgblk.msglen--; /* subtract the size of the dot escape */
1360 msgblk.msglen += linelen;
1362 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1363 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1364 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1367 * Soft linebreak, but less than 200 bytes left in
1368 * input buffer. Rather than doing a buffer overrun,
1369 * ignore the soft linebreak, NL-terminate data and
1370 * deliver what we have now.
1371 * (Who writes lines longer than 2K anyway?)
1373 *inbufp = '\n'; *(inbufp+1) = '\0';
1378 /* ship out the text line */
1379 if (forward && (!issoftline))
1384 /* guard against very long lines */
1385 buf[MSGBUFSIZE+1] = '\r';
1386 buf[MSGBUFSIZE+2] = '\n';
1387 buf[MSGBUFSIZE+3] = '\0';
1389 n = stuffline(ctl, buf);
1393 report(stdout, GT_("writing message text\n"));
1397 else if (outlevel >= O_VERBOSE && !isafile(1))
1408 void init_transact(const struct method *proto)
1409 /* initialize state for the send and receive functions */
1412 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1413 protocol = (struct method *)proto;
1416 static void enshroud(char *buf)
1417 /* shroud a password in the given buffer */
1421 if (shroud[0] && (cp = strstr(buf, shroud)))
1425 sp = cp + strlen(shroud);
1433 #if defined(HAVE_STDARG_H)
1434 void gen_send(int sock, const char *fmt, ... )
1436 void gen_send(sock, fmt, va_alist)
1437 int sock; /* socket to which server is connected */
1438 const char *fmt; /* printf-style format */
1441 /* assemble command in printf(3) style and send to the server */
1443 char buf [MSGBUFSIZE+1];
1446 if (protocol->tagged && !suppress_tags)
1447 (void) sprintf(buf, "%s ", GENSYM);
1451 #if defined(HAVE_STDARG_H)
1456 #ifdef HAVE_VSNPRINTF
1457 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1459 vsprintf(buf + strlen(buf), fmt, ap);
1463 #ifdef HAVE_SNPRINTF
1464 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1466 strcat(buf, "\r\n");
1467 #endif /* HAVE_SNPRINTF */
1468 SockWrite(sock, buf, strlen(buf));
1470 if (outlevel >= O_MONITOR)
1473 buf[strlen(buf)-2] = '\0';
1474 report(stdout, "%s> %s\n", protocol->name, buf);
1478 int gen_recv(sock, buf, size)
1479 /* get one line of input from the server */
1480 int sock; /* socket to which server is connected */
1481 char *buf; /* buffer to receive input */
1482 int size; /* length of buffer */
1484 int oldphase = phase; /* we don't have to be re-entrant */
1486 phase = SERVER_WAIT;
1487 set_timeout(mytimeout);
1488 if (SockRead(sock, buf, size) == -1)
1495 return(PS_IDLETIMEOUT);
1503 if (buf[strlen(buf)-1] == '\n')
1504 buf[strlen(buf)-1] = '\0';
1505 if (buf[strlen(buf)-1] == '\r')
1506 buf[strlen(buf)-1] = '\0';
1507 if (outlevel >= O_MONITOR)
1508 report(stdout, "%s< %s\n", protocol->name, buf);
1514 #if defined(HAVE_STDARG_H)
1515 int gen_transact(int sock, const char *fmt, ... )
1517 int gen_transact(int sock, fmt, va_alist)
1518 int sock; /* socket to which server is connected */
1519 const char *fmt; /* printf-style format */
1522 /* assemble command in printf(3) style, send to server, accept a response */
1525 char buf [MSGBUFSIZE+1];
1527 int oldphase = phase; /* we don't have to be re-entrant */
1529 phase = SERVER_WAIT;
1531 if (protocol->tagged && !suppress_tags)
1532 (void) sprintf(buf, "%s ", GENSYM);
1536 #if defined(HAVE_STDARG_H)
1541 #ifdef HAVE_VSNPRINTF
1542 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1544 vsprintf(buf + strlen(buf), fmt, ap);
1548 #ifdef HAVE_SNPRINTF
1549 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1551 strcat(buf, "\r\n");
1552 #endif /* HAVE_SNPRINTF */
1553 SockWrite(sock, buf, strlen(buf));
1555 if (outlevel >= O_MONITOR)
1558 buf[strlen(buf)-2] = '\0';
1559 report(stdout, "%s> %s\n", protocol->name, buf);
1562 /* we presume this does its own response echoing */
1563 ok = (protocol->parse_response)(sock, buf);
1569 /* transact.c ends here */