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);
458 memcpy(line + linelen - n, buf, n);
459 ch = ' '; /* So the next iteration starts */
464 /* lines may not be properly CRLF terminated; fix this for qmail */
465 /* we don't want to overflow the buffer here */
466 if (ctl->forcecr && buf[n-1] == '\n' && (n == 1 || buf[n-2] != '\r'))
469 rline = (char *) realloc(line, linelen + 2);
476 memcpy(line + linelen - n, buf, n - 1);
477 tcp = line + linelen - 1;
486 rline = (char *) realloc(line, linelen + 1);
493 memcpy(line + linelen - n, buf, n + 1);
496 /* check for end of headers */
497 if (end_of_header(line))
499 if (linelen != strlen (line))
502 goto process_headers;
506 * Check for end of message immediately. If one of your folders
507 * has been mangled, the delimiter may occur directly after the
510 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
512 if (outlevel > O_SILENT)
514 GT_("message delimiter found while scanning headers\n"));
515 if (suppress_readbody)
516 *suppress_readbody = TRUE;
517 if (linelen != strlen (line))
520 goto process_headers;
524 * At least one brain-dead website (netmind.com) is known to
525 * send out robotmail that's missing the RFC822 delimiter blank
526 * line before the body! Without this check fetchmail segfaults.
527 * With it, we treat such messages as spam and refuse them.
529 if (!refuse_mail && !isspace(line[0]) && !strchr(line, ':'))
531 if (linelen != strlen (line))
533 if (outlevel > O_SILENT)
535 GT_("incorrect header line found while scanning headers\n"));
536 if (outlevel >= O_VERBOSE)
537 report (stdout, GT_("line: %s"), line);
541 /* check for RFC822 continuations */
542 set_timeout(mytimeout);
546 (ch == ' ' || ch == '\t'); /* continuation to next line? */
548 /* write the message size dots */
549 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
551 sizeticker += linelen;
552 while (sizeticker >= SIZETICKER)
554 if ((!run.use_syslog && !isafile(1)) || run.showdots)
559 sizeticker -= SIZETICKER;
563 * Decode MIME encoded headers. We MUST do this before
564 * looking at the Content-Type / Content-Transfer-Encoding
565 * headers (RFC 2046).
567 if ( ctl->mimedecode )
571 /* the line is now shorter. So we retrace back till we find our terminating
572 * combination \n\0, we move backwards to make sure that we don't catch som
573 * \n\0 stored in the decoded part of the message */
574 for(tcp = line + linelen - 1; tcp > line && (*tcp != 0 || tcp[-1] != '\n'); tcp--);
575 if(tcp > line) linelen = tcp - line;
579 /* skip processing if we are going to retain or refuse this mail */
580 if (retain_mail || refuse_mail)
586 /* we see an ordinary (non-header, non-message-delimiter line */
587 if (linelen != strlen (line))
590 /* save the message's ID, we may use it for killing duplicates later */
591 if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
592 ctl->thisid = xstrdup(line);
595 * The University of Washington IMAP server (the reference
596 * implementation of IMAP4 written by Mark Crispin) relies
597 * on being able to keep base-UID information in a special
598 * message at the head of the mailbox. This message should
599 * neither be deleted nor forwarded.
603 * We disable this check under POP2 because there's no way to
604 * prevent deletion of the message. So at least we ought to
605 * forward it to the user so he or she will have some clue
606 * that things have gone awry.
609 if (strncmp(protocol->service, "pop2", 4))
610 #else /* INET6_ENABLE */
611 if (protocol->port != 109)
612 #endif /* INET6_ENABLE */
613 #endif /* POP2_ENABLE */
614 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
621 * This code prevents fetchmail from becoming an accessory after
622 * the fact to upstream sendmails with the `E' option on. It also
623 * copes with certain brain-dead POP servers (like NT's) that pass
624 * through Unix from_ lines.
626 * Either of these bugs can result in a non-RFC822 line at the
627 * beginning of the headers. If fetchmail just passes it
628 * through, the client listener may think the message has *no*
629 * headers (since the first) line it sees doesn't look
630 * RFC822-conformant) and fake up a set.
632 * What the user would see in this case is bogus (synthesized)
633 * headers, followed by a blank line, followed by the >From,
634 * followed by the real headers, followed by a blank line,
637 * We forestall this lossage by tossing anything that looks
638 * like an escaped or passed-through From_ line in headers.
639 * These aren't RFC822 so our conscience is clear...
641 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
648 * We remove all Delivered-To: headers.
650 * This is to avoid false mail loops messages when delivering
651 * local messages to and from a Postfix/qmail mailserver.
653 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
663 * If we see a Status line, it may have been inserted by an MUA
664 * on the mail host, or it may have been inserted by the server
665 * program after the headers in the transaction stream. This
666 * can actually hose some new-mail notifiers such as xbuffy,
667 * which assumes any Status line came from a *local* MDA and
668 * therefore indicates that the message has been seen.
670 * Some buggy POP servers (including at least the 3.3(20)
671 * version of the one distributed with IMAP) insert empty
672 * Status lines in the transaction stream; we'll chuck those
673 * unconditionally. Nonempty ones get chucked if the user
674 * turns on the dropstatus flag.
679 if (!strncasecmp(line, "Status:", 7))
681 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
686 while (*cp && isspace(*cp)) cp++;
687 if (!*cp || ctl->dropstatus)
696 line = reply_hack(line, ctl->server.truename);
699 * OK, this is messy. If we're forwarding by SMTP, it's the
700 * SMTP-receiver's job (according to RFC821, page 22, section
701 * 4.1.1) to generate a Return-Path line on final delivery.
702 * The trouble is, we've already got one because the
703 * mailserver's SMTP thought *it* was responsible for final
706 * Stash away the contents of Return-Path (as modified by reply_hack)
707 * for use in generating MAIL FROM later on, then prevent the header
708 * from being saved with the others. In effect, we strip it off here.
710 * If the SMTP server conforms to the standards, and fetchmail gets the
711 * envelope sender from the Return-Path, the new Return-Path should be
712 * exactly the same as the original one.
714 * We do *not* want to ignore empty Return-Path headers. These should
715 * be passed through as a way of indicating that a message should
716 * not trigger bounces if delivery fails. What we *do* need to do is
717 * make sure we never try to rewrite such a blank Return-Path. We
718 * handle this with a check for <> in the rewrite logic above.
720 * Also, if an email has multiple Return-Path: statement, we only
721 * read the first occurance, as some spam email has more than one
725 if ((already_has_return_path==FALSE) && !strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
727 already_has_return_path = TRUE;
728 if (cp[0]=='\0') /* nxtaddr() strips the brackets... */
730 strncpy(msgblk.return_path, cp, sizeof(msgblk.return_path));
731 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
741 msgblk.headers = xmalloc(oldlen + 1);
742 (void) memcpy(msgblk.headers, line, linelen);
743 msgblk.headers[oldlen] = '\0';
745 line = msgblk.headers;
752 newlen = oldlen + linelen;
753 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
754 if (newhdrs == NULL) {
758 msgblk.headers = newhdrs;
759 memcpy(msgblk.headers + oldlen, line, linelen);
760 msgblk.headers[newlen] = '\0';
762 line = msgblk.headers + oldlen;
766 /* find offsets of various special headers */
767 if (!strncasecmp("From:", line, 5))
768 from_offs = (line - msgblk.headers);
769 else if (!strncasecmp("Reply-To:", line, 9))
770 reply_to_offs = (line - msgblk.headers);
771 else if (!strncasecmp("Resent-From:", line, 12))
772 resent_from_offs = (line - msgblk.headers);
773 else if (!strncasecmp("Apparently-From:", line, 16))
774 app_from_offs = (line - msgblk.headers);
776 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
778 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
779 * that Sender: *doesn't* have to be a working email address.
781 * The definition of the Sender header in RFC822 says, in
782 * part, "The Sender mailbox specification includes a word
783 * sequence which must correspond to a specific agent (i.e., a
784 * human user or a computer program) rather than a standard
785 * address." That implies that the contents of the Sender
786 * field don't need to be a legal email address at all So
787 * ignore any Sender or Resent-Sender lines unless they
790 * (RFC2822 says the contents of Sender must be a valid mailbox
791 * address, which is also what RFC822 4.4.4 implies.)
793 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
794 sender_offs = (line - msgblk.headers);
795 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
796 resent_sender_offs = (line - msgblk.headers);
799 else if (!strncasecmp("Message-Id:", line, 11))
801 if (ctl->server.uidl)
805 line[IDLEN+12] = 0; /* prevent stack overflow */
806 sscanf(line+12, "%s", id);
807 if (!str_find( &ctl->newsaved, num))
809 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
810 new->val.status.num = num;
814 #endif /* __UNUSED__ */
816 /* if multidrop is on, gather addressee headers */
819 if (!strncasecmp("To:", line, 3)
820 || !strncasecmp("Cc:", line, 3)
821 || !strncasecmp("Bcc:", line, 4)
822 || !strncasecmp("Apparently-To:", line, 14))
824 *to_chainptr = xmalloc(sizeof(struct addrblk));
825 (*to_chainptr)->offset = (line - msgblk.headers);
826 to_chainptr = &(*to_chainptr)->next;
830 else if (!strncasecmp("Resent-To:", line, 10)
831 || !strncasecmp("Resent-Cc:", line, 10)
832 || !strncasecmp("Resent-Bcc:", line, 11))
834 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
835 (*resent_to_chainptr)->offset = (line - msgblk.headers);
836 resent_to_chainptr = &(*resent_to_chainptr)->next;
837 *resent_to_chainptr = NULL;
840 else if (ctl->server.envelope != STRING_DISABLED)
842 if (ctl->server.envelope
843 && strcasecmp(ctl->server.envelope, "Received"))
845 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
847 strlen(ctl->server.envelope)))
849 if (skipcount++ < ctl->server.envskip)
851 env_offs = (line - msgblk.headers);
854 else if (!received_for && !strncasecmp("Received:", line, 9))
856 if (skipcount++ < ctl->server.envskip)
858 received_for = parse_received(ctl, line);
868 free(msgblk.headers);
869 msgblk.headers = NULL;
875 * When mail delivered to a multidrop mailbox on the server is
876 * addressed to multiple people on the client machine, there will
877 * be one copy left in the box for each recipient. This is not a
878 * problem if we have the actual recipient address to dispatch on
879 * (e.g. because we've mined it out of sendmail trace headers, or
880 * a qmail Delivered-To line, or a declared sender envelope line).
882 * But if we're mining addressees out of the To/Cc/Bcc fields, and
883 * if the mail is addressed to N people, each recipient will
884 * get N copies. This is bad when N > 1.
886 * Foil this by suppressing all but one copy of a message with
887 * a given Message-ID. The accept_count test ensures that
888 * multiple pieces of email with the same Message-ID, each
889 * with a *single* addressee (the N == 1 case), won't be
892 * Note: This implementation only catches runs of successive
893 * messages with the same ID, but that should be good
894 * enough. A more general implementation would have to store
895 * ever-growing lists of seen message-IDs; in a long-running
896 * daemon this would turn into a memory leak even if the
897 * implementation were perfect.
899 * Don't mess with this code casually. It would be way too easy
900 * to break it in a way that blackholed mail. Better to pass
901 * the occasional duplicate than to do that...
903 if (!received_for && env_offs == -1 && !delivered_to)
905 if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
907 if (accept_count > 1)
914 ctl->lastid = ctl->thisid;
920 * Hack time. If the first line of the message was blank, with no headers
921 * (this happens occasionally due to bad gatewaying software) cons up
922 * a set of fake headers.
924 * If you modify the fake header template below, be sure you don't
925 * make either From or To address @-less, otherwise the reply_hack
926 * logic will do bad things.
928 if (msgblk.headers == (char *)NULL)
931 snprintf(buf, sizeof(buf),
934 #endif /* HAVE_SNPRINTF */
935 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
936 user, fetchmailhost, ctl->remotename, ctl->server.truename);
937 msgblk.headers = xstrdup(buf);
941 * We can now process message headers before reading the text.
942 * In fact we have to, as this will tell us where to forward to.
945 /* Check for MIME headers indicating possible 8-bit data */
946 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
949 if (ctl->server.sdps && sdps_envfrom)
951 /* We have the real envelope return-path, stored out of band by
952 * SDPS - that's more accurate than any header is going to be.
954 strcpy(msgblk.return_path, sdps_envfrom);
957 #endif /* SDPS_ENABLE */
959 * If there is a Return-Path address on the message, this was
960 * almost certainly the MAIL FROM address given the originating
961 * sendmail. This is the best thing to use for logging the
962 * message origin (it sets up the right behavior for bounces and
963 * mailing lists). Otherwise, fall down to the next available
964 * envelope address (which is the most probable real sender).
965 * *** The order is important! ***
966 * This is especially useful when receiving mailing list
967 * messages in multidrop mode. if a local address doesn't
968 * exist, the bounce message won't be returned blindly to the
969 * author or to the list itself but rather to the list manager
970 * (ex: specified by "Sender:") which is much less annoying. This
971 * is true for most mailing list packages.
973 if( !msgblk.return_path[0] ){
975 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
976 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
977 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
978 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
979 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
980 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
981 /* multi-line MAIL FROM addresses confuse SMTP terribly */
982 if (ap && !strchr(ap, '\n')) {
983 strncpy(msgblk.return_path, ap, sizeof(msgblk.return_path));
984 msgblk.return_path[sizeof(msgblk.return_path)-1] = '\0';
988 /* cons up a list of local recipients */
989 msgblk.recipients = (struct idlist *)NULL;
990 accept_count = reject_count = 0;
991 /* is this a multidrop box? */
995 if (ctl->server.sdps && sdps_envto)
997 /* We have the real envelope recipient, stored out of band by
998 * SDPS - that's more accurate than any header is going to be.
1000 find_server_names(sdps_envto, ctl, &msgblk.recipients);
1003 #endif /* SDPS_ENABLE */
1004 if (env_offs > -1) /* We have the actual envelope addressee */
1005 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
1006 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
1007 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
1009 find_server_names(delivered_to, ctl, &msgblk.recipients);
1011 delivered_to = NULL;
1013 else if (received_for)
1015 * We have the Received for addressee.
1016 * It has to be a mailserver address, or we
1017 * wouldn't have got here.
1018 * We use find_server_names() to let local
1019 * hostnames go through.
1021 find_server_names(received_for, ctl, &msgblk.recipients);
1025 * We haven't extracted the envelope address.
1026 * So check all the "Resent-To" header addresses if
1027 * they exist. If and only if they don't, consider
1028 * the "To" addresses.
1030 register struct addrblk *nextptr;
1031 if (resent_to_addrchain) {
1032 /* delete the "To" chain and substitute it
1033 * with the "Resent-To" list
1035 while (to_addrchain) {
1036 nextptr = to_addrchain->next;
1038 to_addrchain = nextptr;
1040 to_addrchain = resent_to_addrchain;
1041 resent_to_addrchain = NULL;
1043 /* now look for remaining adresses */
1044 while (to_addrchain) {
1045 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
1046 nextptr = to_addrchain->next;
1048 to_addrchain = nextptr;
1053 no_local_matches = TRUE;
1054 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
1055 if (outlevel >= O_DEBUG)
1057 GT_("no local matches, forwarding to %s\n"),
1061 else /* it's a single-drop box, use first localname */
1062 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
1066 * Time to either address the message or decide we can't deliver it yet.
1068 if (ctl->errcount > olderrs) /* there were DNS errors above */
1070 if (outlevel >= O_DEBUG)
1072 GT_("forwarding and deletion suppressed due to DNS errors\n"));
1073 free(msgblk.headers);
1074 msgblk.headers = NULL;
1075 free_str_list(&msgblk.recipients);
1076 return(PS_TRANSIENT);
1080 /* set up stuffline() so we can deliver the message body through it */
1081 if ((n = open_sink(ctl, &msgblk,
1082 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1084 free(msgblk.headers);
1085 msgblk.headers = NULL;
1086 free_str_list(&msgblk.recipients);
1093 * Some server/sendmail combinations cause problems when our
1094 * synthetic Received line is before the From header. Cope
1097 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1098 rcv = msgblk.headers;
1099 /* handle ">Received:" lines too */
1100 while (rcv > msgblk.headers && rcv[-1] != '\n')
1102 if (rcv > msgblk.headers)
1107 n = stuffline(ctl, msgblk.headers);
1110 if (!run.invisible && n != -1)
1112 /* utter any per-message Received information we need here */
1113 if (ctl->server.trueaddr) {
1114 #ifdef HAVE_SNPRINTF
1115 snprintf(buf, sizeof(buf),
1118 #endif /* HAVE_SNPRINTF */
1119 "Received: from %s [%u.%u.%u.%u]\r\n",
1120 ctl->server.truename,
1121 (unsigned char)ctl->server.trueaddr[0],
1122 (unsigned char)ctl->server.trueaddr[1],
1123 (unsigned char)ctl->server.trueaddr[2],
1124 (unsigned char)ctl->server.trueaddr[3]);
1126 #ifdef HAVE_SNPRINTF
1127 snprintf(buf, sizeof(buf),
1130 #endif /* HAVE_SNPRINTF */
1131 "Received: from %s\r\n", ctl->server.truename);
1133 n = stuffline(ctl, buf);
1137 * This header is technically invalid under RFC822.
1138 * POP3, IMAP, etc. are not legal mail-parameter values.
1140 #ifdef HAVE_SNPRINTF
1141 snprintf(buf, sizeof(buf),
1144 #endif /* HAVE_SNPRINTF */
1145 "\tby %s with %s (fetchmail-%s",
1149 if (ctl->tracepolls)
1151 sprintf(buf + strlen(buf), " polling %s account %s",
1152 ctl->server.pollname,
1155 #ifdef HAVE_SNPRINTF
1156 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1158 strcat(buf, ")\r\n");
1159 #endif /* HAVE_SNPRINTF */
1160 n = stuffline(ctl, buf);
1164 if (good_addresses == 0)
1166 #ifdef HAVE_SNPRINTF
1167 snprintf(buf+1, sizeof(buf)-1,
1170 #endif /* HAVE_SNPRINTF */
1171 "for %s (by default); ",
1172 rcpt_address (ctl, run.postmaster, 0));
1174 else if (good_addresses == 1)
1176 for (idp = msgblk.recipients; idp; idp = idp->next)
1177 if (idp->val.status.mark == XMIT_ACCEPT)
1178 break; /* only report first address */
1179 #ifdef HAVE_SNPRINTF
1180 snprintf(buf+1, sizeof(buf)-1,
1183 #endif /* HAVE_SNPRINTF */
1184 "for %s", rcpt_address (ctl, idp->id, 1));
1185 sprintf(buf+strlen(buf), " (%s); ",
1186 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1191 #ifdef HAVE_SNPRINTF
1192 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1195 strcat(buf, rfc822timestamp());
1196 strcat(buf, "\r\n");
1197 #endif /* HAVE_SNPRINTF */
1198 n = stuffline(ctl, buf);
1204 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1208 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1210 free(msgblk.headers);
1211 msgblk.headers = NULL;
1212 free_str_list(&msgblk.recipients);
1215 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1218 /* write error notifications */
1219 if (no_local_matches || has_nuls || bad_addresses)
1222 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1225 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1226 if (no_local_matches)
1228 if (reject_count != 1)
1229 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1232 for (idp = msgblk.recipients; idp; idp = idp->next)
1233 if (idp->val.status.mark == XMIT_REJECT)
1235 #ifdef HAVE_SNPRINTF
1236 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1238 sprintf(errhd+strlen(errhd),
1239 #endif /* HAVE_SNPRINTF */
1240 GT_("recipient address %s didn't match any local name"), idp->id);
1246 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1247 #ifdef HAVE_SNPRINTF
1248 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1249 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1251 strcat(errhd, "; ");
1253 #endif /* HAVE_SNPRINTF */
1254 GT_("message has embedded NULs"));
1259 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1260 #ifdef HAVE_SNPRINTF
1261 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd), "; ");
1262 snprintf(errhd+strlen(errhd), sizeof(errhd)-strlen(errhd),
1264 strcat(errhd, "; ");
1266 #endif /* HAVE_SNPRINTF */
1267 GT_("SMTP listener rejected local recipient addresses: "));
1268 errlen = strlen(errhd);
1269 for (idp = msgblk.recipients; idp; idp = idp->next)
1270 if (idp->val.status.mark == XMIT_RCPTBAD)
1271 errlen += strlen(idp->id) + 2;
1273 xalloca(errmsg, char *, errlen+3);
1274 (void) strcpy(errmsg, errhd);
1275 for (idp = msgblk.recipients; idp; idp = idp->next)
1276 if (idp->val.status.mark == XMIT_RCPTBAD)
1278 strcat(errmsg, idp->id);
1280 strcat(errmsg, ", ");
1285 strcat(errmsg, "\r\n");
1287 /* ship out the error line */
1288 stuffline(ctl, errmsg);
1291 /* issue the delimiter line */
1296 stuffline(ctl, buf);
1301 int readbody(int sock, struct query *ctl, flag forward, int len)
1302 /* read and dispose of a message body presented on sock */
1303 /* ctl: query control record */
1304 /* sock: to which the server is connected */
1305 /* len: length of message */
1306 /* forward: TRUE to forward */
1309 unsigned char buf[MSGBUFSIZE+4];
1310 unsigned char *inbufp = buf;
1311 flag issoftline = FALSE;
1314 * Pass through the text lines in the body.
1316 * Yes, this wants to be ||, not &&. The problem is that in the most
1317 * important delimited protocol, POP3, the length is not reliable.
1318 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1319 * So, for delimited protocols we need to ignore the length here and
1320 * instead drop out of the loop with a break statement when we see
1321 * the message delimiter.
1323 while (protocol->delimited || len > 0)
1325 set_timeout(mytimeout);
1326 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1334 /* write the message size dots */
1337 sizeticker += linelen;
1338 while (sizeticker >= SIZETICKER)
1340 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1345 sizeticker -= SIZETICKER;
1350 /* check for end of message */
1351 if (protocol->delimited && *inbufp == '.')
1353 if (EMPTYLINE(inbufp+1))
1356 msgblk.msglen--; /* subtract the size of the dot escape */
1359 msgblk.msglen += linelen;
1361 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1362 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1363 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1366 * Soft linebreak, but less than 200 bytes left in
1367 * input buffer. Rather than doing a buffer overrun,
1368 * ignore the soft linebreak, NL-terminate data and
1369 * deliver what we have now.
1370 * (Who writes lines longer than 2K anyway?)
1372 *inbufp = '\n'; *(inbufp+1) = '\0';
1377 /* ship out the text line */
1378 if (forward && (!issoftline))
1383 /* guard against very long lines */
1384 buf[MSGBUFSIZE+1] = '\r';
1385 buf[MSGBUFSIZE+2] = '\n';
1386 buf[MSGBUFSIZE+3] = '\0';
1388 n = stuffline(ctl, buf);
1392 report(stdout, GT_("writing message text\n"));
1396 else if (outlevel >= O_VERBOSE && !isafile(1))
1407 void init_transact(const struct method *proto)
1408 /* initialize state for the send and receive functions */
1411 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1412 protocol = (struct method *)proto;
1415 static void enshroud(char *buf)
1416 /* shroud a password in the given buffer */
1420 if (shroud[0] && (cp = strstr(buf, shroud)))
1424 sp = cp + strlen(shroud);
1432 #if defined(HAVE_STDARG_H)
1433 void gen_send(int sock, const char *fmt, ... )
1435 void gen_send(sock, fmt, va_alist)
1436 int sock; /* socket to which server is connected */
1437 const char *fmt; /* printf-style format */
1440 /* assemble command in printf(3) style and send to the server */
1442 char buf [MSGBUFSIZE+1];
1445 if (protocol->tagged && !suppress_tags)
1446 (void) sprintf(buf, "%s ", GENSYM);
1450 #if defined(HAVE_STDARG_H)
1455 #ifdef HAVE_VSNPRINTF
1456 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1458 vsprintf(buf + strlen(buf), fmt, ap);
1462 #ifdef HAVE_SNPRINTF
1463 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1465 strcat(buf, "\r\n");
1466 #endif /* HAVE_SNPRINTF */
1467 SockWrite(sock, buf, strlen(buf));
1469 if (outlevel >= O_MONITOR)
1472 buf[strlen(buf)-2] = '\0';
1473 report(stdout, "%s> %s\n", protocol->name, buf);
1477 int gen_recv(sock, buf, size)
1478 /* get one line of input from the server */
1479 int sock; /* socket to which server is connected */
1480 char *buf; /* buffer to receive input */
1481 int size; /* length of buffer */
1483 int oldphase = phase; /* we don't have to be re-entrant */
1485 phase = SERVER_WAIT;
1486 set_timeout(mytimeout);
1487 if (SockRead(sock, buf, size) == -1)
1494 return(PS_IDLETIMEOUT);
1502 if (buf[strlen(buf)-1] == '\n')
1503 buf[strlen(buf)-1] = '\0';
1504 if (buf[strlen(buf)-1] == '\r')
1505 buf[strlen(buf)-1] = '\0';
1506 if (outlevel >= O_MONITOR)
1507 report(stdout, "%s< %s\n", protocol->name, buf);
1513 #if defined(HAVE_STDARG_H)
1514 int gen_transact(int sock, const char *fmt, ... )
1516 int gen_transact(int sock, fmt, va_alist)
1517 int sock; /* socket to which server is connected */
1518 const char *fmt; /* printf-style format */
1521 /* assemble command in printf(3) style, send to server, accept a response */
1524 char buf [MSGBUFSIZE+1];
1526 int oldphase = phase; /* we don't have to be re-entrant */
1528 phase = SERVER_WAIT;
1530 if (protocol->tagged && !suppress_tags)
1531 (void) sprintf(buf, "%s ", GENSYM);
1535 #if defined(HAVE_STDARG_H)
1540 #ifdef HAVE_VSNPRINTF
1541 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1543 vsprintf(buf + strlen(buf), fmt, ap);
1547 #ifdef HAVE_SNPRINTF
1548 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1550 strcat(buf, "\r\n");
1551 #endif /* HAVE_SNPRINTF */
1552 SockWrite(sock, buf, strlen(buf));
1554 if (outlevel >= O_MONITOR)
1557 buf[strlen(buf)-2] = '\0';
1558 report(stdout, "%s> %s\n", protocol->name, buf);
1561 /* we presume this does its own response echoing */
1562 ok = (protocol->parse_response)(sock, buf);
1568 /* transact.c ends here */