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]; /* 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 * If the name of the user begins with a qmail virtual
97 * domain prefix, ignore the prefix. Doing this here
98 * means qvirtual will work either with ordinary name
99 * mapping or with a localdomains option.
101 if (ctl->server.qvirtual)
103 int sl = strlen(ctl->server.qvirtual);
105 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
109 if ((atsign = strchr(cp, '@'))) {
113 * Does a trailing segment of the hostname match something
114 * on the localdomains list? If so, save the whole name
117 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
120 rhs = atsign + (strlen(atsign) - strlen(idp->id));
122 (rhs[-1] == '.' || rhs[-1] == '@') &&
123 strcasecmp(rhs, idp->id) == 0)
125 if (outlevel >= O_DEBUG)
126 report(stdout, GT_("passed through %s matching %s\n"),
128 save_str(xmit_names, cp, XMIT_ACCEPT);
134 /* if we matched a local domain, idp != NULL */
138 * Check to see if the right-hand part is an alias
139 * or MX equivalent of the mailserver. If it's
140 * not, skip this name. If it is, we'll keep
141 * going and try to find a mapping to a client name.
143 if (!is_host_alias(atsign+1, ctl))
145 save_str(xmit_names, cp, XMIT_REJECT);
151 map_name(cp, ctl, xmit_names);
159 * Return zero on a syntactically invalid address, nz on a valid one.
161 * This used to be strchr(a, '.'), but it turns out that lines like this
163 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
164 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
166 * are not uncommon. So now we just check that the following token is
167 * not itself an email address.
169 #define VALID_ADDRESS(a) !strchr(a, '@')
171 static char *parse_received(struct query *ctl, char *bufp)
172 /* try to extract real address from the Received line */
173 /* If a valid Received: line is found, we return the full address in
174 * a buffer which can be parsed from nxtaddr(). This is to ansure that
175 * the local domain part of the address can be passed along in
176 * find_server_names() if it contains one.
177 * Note: We should return a dummy header containing the address
178 * which makes nxtaddr() behave correctly.
181 char *base, *ok = (char *)NULL;
182 static char rbuf[HOSTLEN + USERNAMELEN + 4];
185 * Try to extract the real envelope addressee. We look here
186 * specifically for the mailserver's Received line.
187 * Note: this will only work for sendmail, or an MTA that
188 * shares sendmail's convention for embedding the envelope
189 * address in the Received line. Sendmail itself only
190 * does this when the mail has a single recipient.
192 if (outlevel >= O_DEBUG)
193 report(stdout, GT_("analyzing Received line:\n%s"), bufp);
195 /* search for whitepace-surrounded "by" followed by valid address */
196 for (base = bufp; ; base = ok + 2)
198 if (!(ok = strstr(base, "by")))
200 else if (!isspace(ok[-1]) || !isspace(ok[2]))
206 /* extract space-delimited token after "by" */
207 for (sp = ok + 2; isspace(*sp); sp++)
210 for (; !isspace(*sp); sp++)
214 /* look for valid address */
215 if (VALID_ADDRESS(rbuf))
218 ok = sp - 1; /* arrange to skip this token */
224 * If it's a DNS name of the mail server, look for the
225 * recipient name after a following "for". Otherwise
228 if (is_host_alias(rbuf, ctl))
230 if (outlevel >= O_DEBUG)
232 GT_("line accepted, %s is an alias of the mailserver\n"), rbuf);
236 if (outlevel >= O_DEBUG)
238 GT_("line rejected, %s is not an alias of the mailserver\n"),
243 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
244 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
246 if (!(ok = strstr(base, "for")))
248 else if (!isspace(ok[-1]) || !isspace(ok[3]))
254 /* extract space-delimited token after "for" */
255 for (sp = ok + 3; isspace(*sp); sp++)
258 for (; !isspace(*sp); sp++)
262 if (strchr(rbuf, '@'))
265 ok = sp - 1; /* arrange to skip this token */
270 flag want_gt = FALSE;
273 /* char after "for" could be space or a continuation newline */
274 for (sp = ok + 4; isspace(*sp); sp++)
277 *tp++ = ':'; /* Here is the hack. This is to be friends */
278 *tp++ = ' '; /* with nxtaddr()... */
284 while (*sp == '@') /* skip routes */
285 while (*sp && *sp++ != ':')
288 && (want_gt ? (*sp != '>') : !isspace(*sp))
294 /* uh oh -- whitespace here can't be right! */
300 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
308 if (outlevel >= O_DEBUG)
309 report(stdout, GT_("no Received address found\n"));
314 if (outlevel >= O_DEBUG) {
315 char *lf = rbuf + strlen(rbuf)-1;
317 if (outlevel >= O_DEBUG)
318 report(stdout, GT_("found Received address `%s'\n"), rbuf+2);
325 /* shared by readheaders and readbody */
326 static int sizeticker;
328 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
330 int readheaders(int sock,
335 /* read message headers and ship to SMTP or MDA */
336 /* sock: to which the server is connected */
337 /* fetchlen: length of message according to fetch response */
338 /* reallen: length of message according to getsizes */
339 /* ctl: query control record */
340 /* num: index of message */
345 struct addrblk *next;
347 struct addrblk *to_addrchain = NULL;
348 struct addrblk **to_chainptr = &to_addrchain;
349 struct addrblk *resent_to_addrchain = NULL;
350 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
352 char buf[MSGBUFSIZE+1];
353 int from_offs, reply_to_offs, resent_from_offs;
354 int app_from_offs, sender_offs, resent_sender_offs;
356 char *received_for, *rcv, *cp, *delivered_to;
357 int n, linelen, oldlen, ch, remaining, skipcount;
359 flag no_local_matches = FALSE;
360 flag headers_ok, has_nuls;
361 int olderrs, good_addresses, bad_addresses;
364 has_nuls = headers_ok = FALSE;
365 msgblk.return_path[0] = '\0';
366 olderrs = ctl->errcount;
368 /* read message headers */
369 msgblk.reallen = reallen;
372 * We used to free the header block unconditionally at the end of
373 * readheaders, but it turns out that if close_sink() hits an error
374 * condition the code for sending bouncemail will actually look
375 * at the freed storage and coredump...
378 free(msgblk.headers);
380 /* initially, no message ID */
385 msgblk.headers = received_for = delivered_to = NULL;
386 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
387 sender_offs = resent_sender_offs = env_offs = -1;
393 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
396 int overlong = FALSE;
398 line = xmalloc(sizeof(buf));
402 set_timeout(mytimeout);
403 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
406 free(msgblk.headers);
407 msgblk.headers = NULL;
415 * Try to gracefully handle the case, where the length of a
416 * line exceeds MSGBUFSIZE.
418 if ( n && buf[n-1] != '\n' ) {
419 unsigned int llen = strlen(line);
421 line = realloc(line, llen + n + 1);
422 strcpy(line + llen, buf);
423 ch = ' '; /* So the next iteration starts */
427 /* lines may not be properly CRLF terminated; fix this for qmail */
430 cp = buf + strlen(buf) - 1;
431 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
440 * Decode MIME encoded headers. We MUST do this before
441 * looking at the Content-Type / Content-Transfer-Encoding
442 * headers (RFC 2046).
444 if ( ctl->mimedecode && overlong ) {
446 * If we received an overlong line, we have to decode the
447 * whole line at once.
449 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
454 if ( ctl->mimedecode )
457 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
461 /* check for end of headers */
465 has_nuls = (linelen != strlen(line));
467 goto process_headers;
471 * Check for end of message immediately. If one of your folders
472 * has been mangled, the delimiter may occur directly after the
475 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
477 has_nuls = (linelen != strlen(line));
479 goto process_headers;
483 * At least one brain-dead website (netmind.com) is known to
484 * send out robotmail that's missing the RFC822 delimiter blank
485 * line before the body! Without this check fetchmail segfaults.
486 * With it, we treat such messages as though they had the missing
489 if (!isspace(line[0]) && !strchr(line, ':'))
492 has_nuls = (linelen != strlen(line));
494 goto process_headers;
497 /* check for RFC822 continuations */
498 set_timeout(mytimeout);
502 (ch == ' ' || ch == '\t'); /* continuation to next line? */
504 /* write the message size dots */
505 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
507 sizeticker += linelen;
508 while (sizeticker >= SIZETICKER)
510 if ((!run.use_syslog && !isafile(1)) || run.showdots)
515 sizeticker -= SIZETICKER;
519 /* we see an ordinary (non-header, non-message-delimiter line */
520 has_nuls = (linelen != strlen(line));
522 /* save the message's ID, we may use it for killing duplicates later */
523 if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
524 ctl->thisid = xstrdup(line);
527 * The University of Washington IMAP server (the reference
528 * implementation of IMAP4 written by Mark Crispin) relies
529 * on being able to keep base-UID information in a special
530 * message at the head of the mailbox. This message should
531 * neither be deleted nor forwarded.
535 * We disable this check under POP2 because there's no way to
536 * prevent deletion of the message. So at least we ought to
537 * forward it to the user so he or she will have some clue
538 * that things have gone awry.
541 if (strncmp(protocol->service, "pop2", 4))
542 #else /* INET6_ENABLE */
543 if (protocol->port != 109)
544 #endif /* INET6_ENABLE */
545 #endif /* POP2_ENABLE */
546 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
548 free(msgblk.headers);
549 msgblk.headers = NULL;
554 * This code prevents fetchmail from becoming an accessory after
555 * the fact to upstream sendmails with the `E' option on. It also
556 * copes with certain brain-dead POP servers (like NT's) that pass
557 * through Unix from_ lines.
559 * Either of these bugs can result in a non-RFC822 line at the
560 * beginning of the headers. If fetchmail just passes it
561 * through, the client listener may think the message has *no*
562 * headers (since the first) line it sees doesn't look
563 * RFC822-conformant) and fake up a set.
565 * What the user would see in this case is bogus (synthesized)
566 * headers, followed by a blank line, followed by the >From,
567 * followed by the real headers, followed by a blank line,
570 * We forestall this lossage by tossing anything that looks
571 * like an escaped or passed-through From_ line in headers.
572 * These aren't RFC822 so our conscience is clear...
574 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
581 * We remove all Delivered-To: headers.
583 * This is to avoid false mail loops messages when delivering
584 * local messages to and from a Postfix/qmail mailserver.
586 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13))
596 * If we see a Status line, it may have been inserted by an MUA
597 * on the mail host, or it may have been inserted by the server
598 * program after the headers in the transaction stream. This
599 * can actually hose some new-mail notifiers such as xbuffy,
600 * which assumes any Status line came from a *local* MDA and
601 * therefore indicates that the message has been seen.
603 * Some buggy POP servers (including at least the 3.3(20)
604 * version of the one distributed with IMAP) insert empty
605 * Status lines in the transaction stream; we'll chuck those
606 * unconditionally. Nonempty ones get chucked if the user
607 * turns on the dropstatus flag.
612 if (!strncasecmp(line, "Status:", 7))
614 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
619 while (*cp && isspace(*cp)) cp++;
620 if (!*cp || ctl->dropstatus)
629 line = reply_hack(line, ctl->server.truename);
632 * OK, this is messy. If we're forwarding by SMTP, it's the
633 * SMTP-receiver's job (according to RFC821, page 22, section
634 * 4.1.1) to generate a Return-Path line on final delivery.
635 * The trouble is, we've already got one because the
636 * mailserver's SMTP thought *it* was responsible for final
639 * Stash away the contents of Return-Path (as modified by reply_hack)
640 * for use in generating MAIL FROM later on, then prevent the header
641 * from being saved with the others. In effect, we strip it off here.
643 * If the SMTP server conforms to the standards, and fetchmail gets the
644 * envelope sender from the Return-Path, the new Return-Path should be
645 * exactly the same as the original one.
647 * We do *not* want to ignore empty Return-Path headers. These should
648 * be passed through as a way of indicating that a message should
649 * not trigger bounces if delivery fails. What we *do* need to do is
650 * make sure we never try to rewrite such a blank Return-Path. We
651 * handle this with a check for <> in the rewrite logic above.
653 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
655 strcpy(msgblk.return_path, cp);
664 oldlen = strlen(line);
665 msgblk.headers = xmalloc(oldlen + 1);
666 (void) strcpy(msgblk.headers, line);
668 line = msgblk.headers;
675 newlen = oldlen + strlen(line);
676 newhdrs = (char *) realloc(msgblk.headers, newlen + 1);
677 if (newhdrs == NULL) {
681 msgblk.headers = newhdrs;
682 strcpy(msgblk.headers + oldlen, line);
684 line = msgblk.headers + oldlen;
688 /* find offsets of various special headers */
689 if (!strncasecmp("From:", line, 5))
690 from_offs = (line - msgblk.headers);
691 else if (!strncasecmp("Reply-To:", line, 9))
692 reply_to_offs = (line - msgblk.headers);
693 else if (!strncasecmp("Resent-From:", line, 12))
694 resent_from_offs = (line - msgblk.headers);
695 else if (!strncasecmp("Apparently-From:", line, 16))
696 app_from_offs = (line - msgblk.headers);
698 * Netscape 4.7 puts "Sender: zap" in mail headers. Perverse...
700 * But a literal reading of RFC822 sec. 4.4.2 supports the idea
701 * that Sender: *doesn't* have to be a working email address.
703 * The definition of the Sender header in RFC822 says, in
704 * part, "The Sender mailbox specification includes a word
705 * sequence which must correspond to a specific agent (i.e., a
706 * human user or a computer program) rather than a standard
707 * address." That implies that the contents of the Sender
708 * field don't need to be a legal email address at all So
709 * ignore any Sender or Resent-Semnder lines unless they
712 * (RFC2822 says the condents of Sender must be a valid mailbox
713 * address, which is also what RFC822 4.4.4 implies.)
715 else if (!strncasecmp("Sender:", line, 7) && (strchr(line, '@') || strchr(line, '!')))
716 sender_offs = (line - msgblk.headers);
717 else if (!strncasecmp("Resent-Sender:", line, 14) && (strchr(line, '@') || strchr(line, '!')))
718 resent_sender_offs = (line - msgblk.headers);
721 else if (!strncasecmp("Message-Id:", line, 11))
723 if (ctl->server.uidl)
727 line[IDLEN+12] = 0; /* prevent stack overflow */
728 sscanf(line+12, "%s", id);
729 if (!str_find( &ctl->newsaved, num))
731 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
732 new->val.status.num = num;
736 #endif /* __UNUSED__ */
738 /* if multidrop is on, gather addressee headers */
741 if (!strncasecmp("To:", line, 3)
742 || !strncasecmp("Cc:", line, 3)
743 || !strncasecmp("Bcc:", line, 4)
744 || !strncasecmp("Apparently-To:", line, 14))
746 *to_chainptr = xmalloc(sizeof(struct addrblk));
747 (*to_chainptr)->offset = (line - msgblk.headers);
748 to_chainptr = &(*to_chainptr)->next;
752 else if (!strncasecmp("Resent-To:", line, 10)
753 || !strncasecmp("Resent-Cc:", line, 10)
754 || !strncasecmp("Resent-Bcc:", line, 11))
756 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
757 (*resent_to_chainptr)->offset = (line - msgblk.headers);
758 resent_to_chainptr = &(*resent_to_chainptr)->next;
759 *resent_to_chainptr = NULL;
762 else if (ctl->server.envelope != STRING_DISABLED)
764 if (ctl->server.envelope
765 && strcasecmp(ctl->server.envelope, "Received"))
767 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
769 strlen(ctl->server.envelope)))
771 if (skipcount++ < ctl->server.envskip)
773 env_offs = (line - msgblk.headers);
776 else if (!received_for && !strncasecmp("Received:", line, 9))
778 if (skipcount++ < ctl->server.envskip)
780 received_for = parse_received(ctl, line);
788 * When mail delivered to a multidrop mailbox on the server is
789 * addressed to multiple people on the client machine, there will
790 * be one copy left in the box for each recipient. This is not a
791 * problem if we have the actual recipient address to dispatch on
792 * (e.g. because we've mined it out of sendmail trace headers, or
793 * a qmail Delivered-To line, or a declared sender envelope line).
795 * But if we're mining addressees out of the To/Cc/Bcc fields, and
796 * if the mail is addressed to N people, each recipient will
797 * get N copies. This is bad when N > 1.
799 * Foil this by suppressing all but one copy of a message with
800 * a given Message-ID. The accept_count test ensures that
801 * multiple pieces of email with the same Message-ID, each
802 * with a *single* addressee (the N == 1 case), won't be
805 * Note: This implementation only catches runs of successive
806 * messages with the same ID, but that should be good
807 * enough. A more general implementation would have to store
808 * ever-growing lists of seen message-IDs; in a long-running
809 * daemon this would turn into a memory leak even if the
810 * implementation were perfect.
812 * Don't mess with this code casually. It would be way too easy
813 * to break it in a way that blackholed mail. Better to pass
814 * the occasional duplicate than to do that...
816 if (!received_for && env_offs == -1 && !delivered_to)
818 if (ctl->lastid && ctl->thisid && !strcasecmp(ctl->lastid, ctl->thisid))
820 if (accept_count > 1)
827 ctl->lastid = ctl->thisid;
833 * We want to detect this early in case there are so few headers that the
834 * dispatch logic barfs.
838 if (outlevel > O_SILENT)
840 GT_("message delimiter found while scanning headers\n"));
844 * Hack time. If the first line of the message was blank, with no headers
845 * (this happens occasionally due to bad gatewaying software) cons up
846 * a set of fake headers.
848 * If you modify the fake header template below, be sure you don't
849 * make either From or To address @-less, otherwise the reply_hack
850 * logic will do bad things.
852 if (msgblk.headers == (char *)NULL)
855 snprintf(buf, sizeof(buf),
858 #endif /* HAVE_SNPRINTF */
859 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
860 user, fetchmailhost, ctl->remotename, ctl->server.truename);
861 msgblk.headers = xstrdup(buf);
865 * We can now process message headers before reading the text.
866 * In fact we have to, as this will tell us where to forward to.
869 /* Check for MIME headers indicating possible 8-bit data */
870 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
873 if (ctl->server.sdps && sdps_envfrom)
875 /* We have the real envelope return-path, stored out of band by
876 * SDPS - that's more accurate than any header is going to be.
878 strcpy(msgblk.return_path, sdps_envfrom);
881 #endif /* SDPS_ENABLE */
883 * If there is a Return-Path address on the message, this was
884 * almost certainly the MAIL FROM address given the originating
885 * sendmail. This is the best thing to use for logging the
886 * message origin (it sets up the right behavior for bounces and
887 * mailing lists). Otherwise, fall down to the next available
888 * envelope address (which is the most probable real sender).
889 * *** The order is important! ***
890 * This is especially useful when receiving mailing list
891 * messages in multidrop mode. if a local address doesn't
892 * exist, the bounce message won't be returned blindly to the
893 * author or to the list itself but rather to the list manager
894 * (ex: specified by "Sender:") which is much less annoying. This
895 * is true for most mailing list packages.
897 if( !msgblk.return_path[0] ){
899 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
900 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
901 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
902 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
903 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
904 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
905 /* multi-line MAIL FROM addresses confuse SMTP terribly */
906 if (ap && !strchr(ap, '\n'))
907 strcpy(msgblk.return_path, ap);
910 /* cons up a list of local recipients */
911 msgblk.recipients = (struct idlist *)NULL;
912 accept_count = reject_count = 0;
913 /* is this a multidrop box? */
917 if (ctl->server.sdps && sdps_envto)
919 /* We have the real envelope recipient, stored out of band by
920 * SDPS - that's more accurate than any header is going to be.
922 find_server_names(sdps_envto, ctl, &msgblk.recipients);
925 #endif /* SDPS_ENABLE */
926 if (env_offs > -1) /* We have the actual envelope addressee */
927 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
928 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
929 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
931 find_server_names(delivered_to, ctl, &msgblk.recipients);
934 else if (received_for)
936 * We have the Received for addressee.
937 * It has to be a mailserver address, or we
938 * wouldn't have got here.
939 * We use find_server_names() to let local
940 * hostnames go through.
942 find_server_names(received_for, ctl, &msgblk.recipients);
946 * We haven't extracted the envelope address.
947 * So check all the "Resent-To" header addresses if
948 * they exist. If and only if they don't, consider
949 * the "To" addresses.
951 register struct addrblk *nextptr;
952 if (resent_to_addrchain) {
953 /* delete the "To" chain and substitute it
954 * with the "Resent-To" list
956 while (to_addrchain) {
957 nextptr = to_addrchain->next;
959 to_addrchain = nextptr;
961 to_addrchain = resent_to_addrchain;
962 resent_to_addrchain = NULL;
964 /* now look for remaining adresses */
965 while (to_addrchain) {
966 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
967 nextptr = to_addrchain->next;
969 to_addrchain = nextptr;
974 no_local_matches = TRUE;
975 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
976 if (outlevel >= O_DEBUG)
978 GT_("no local matches, forwarding to %s\n"),
982 else /* it's a single-drop box, use first localname */
983 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
987 * Time to either address the message or decide we can't deliver it yet.
989 if (ctl->errcount > olderrs) /* there were DNS errors above */
991 if (outlevel >= O_DEBUG)
993 GT_("forwarding and deletion suppressed due to DNS errors\n"));
994 free(msgblk.headers);
995 msgblk.headers = NULL;
996 free_str_list(&msgblk.recipients);
997 return(PS_TRANSIENT);
1001 /* set up stuffline() so we can deliver the message body through it */
1002 if ((n = open_sink(ctl, &msgblk,
1003 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1005 free(msgblk.headers);
1006 msgblk.headers = NULL;
1007 free_str_list(&msgblk.recipients);
1014 * Some server/sendmail combinations cause problems when our
1015 * synthetic Received line is before the From header. Cope
1018 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1019 rcv = msgblk.headers;
1020 /* handle ">Received:" lines too */
1021 while (rcv > msgblk.headers && rcv[-1] != '\n')
1023 if (rcv > msgblk.headers)
1028 n = stuffline(ctl, msgblk.headers);
1031 if (!run.invisible && n != -1)
1033 /* utter any per-message Received information we need here */
1034 if (ctl->server.trueaddr) {
1035 #ifdef HAVE_SNPRINTF
1036 snprintf(buf, sizeof(buf),
1039 #endif /* HAVE_SNPRINTF */
1040 "Received: from %s [%u.%u.%u.%u]\r\n",
1041 ctl->server.truename,
1042 (unsigned char)ctl->server.trueaddr[0],
1043 (unsigned char)ctl->server.trueaddr[1],
1044 (unsigned char)ctl->server.trueaddr[2],
1045 (unsigned char)ctl->server.trueaddr[3]);
1047 #ifdef HAVE_SNPRINTF
1048 snprintf(buf, sizeof(buf),
1051 #endif /* HAVE_SNPRINTF */
1052 "Received: from %s\r\n", ctl->server.truename);
1054 n = stuffline(ctl, buf);
1058 * This header is technically invalid under RFC822.
1059 * POP3, IMAP, etc. are not legal mail-parameter values.
1061 #ifdef HAVE_SNPRINTF
1062 snprintf(buf, sizeof(buf),
1065 #endif /* HAVE_SNPRINTF */
1066 "\tby %s with %s (fetchmail-%s",
1070 if (ctl->tracepolls)
1072 sprintf(buf + strlen(buf), " polling %s account %s",
1073 ctl->server.pollname,
1076 #ifdef HAVE_SNPRINTF
1077 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), ")\r\n");
1079 strcat(buf, ")\r\n");
1080 #endif /* HAVE_SNPRINTF */
1081 n = stuffline(ctl, buf);
1085 if (good_addresses == 0)
1087 #ifdef HAVE_SNPRINTF
1088 snprintf(buf+1, sizeof(buf)-1,
1091 #endif /* HAVE_SNPRINTF */
1092 "for %s@%s (by default); ",
1093 user, ctl->destaddr);
1095 else if (good_addresses == 1)
1097 for (idp = msgblk.recipients; idp; idp = idp->next)
1098 if (idp->val.status.mark == XMIT_ACCEPT)
1099 break; /* only report first address */
1100 if (strchr(idp->id, '@'))
1101 #ifdef HAVE_SNPRINTF
1102 snprintf(buf+1, sizeof(buf)-1,
1105 #endif /* HAVE_SNPRINTF */
1109 * This could be a bit misleading, as destaddr is
1110 * the forwarding host rather than the actual
1111 * destination. Most of the time they coincide.
1113 #ifdef HAVE_SNPRINTF
1114 snprintf(buf+1, sizeof(buf)-1,
1117 #endif /* HAVE_SNPRINTF */
1118 "for %s@%s", idp->id, ctl->destaddr);
1119 sprintf(buf+strlen(buf), " (%s); ",
1120 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1125 #ifdef HAVE_SNPRINTF
1126 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%s\r\n",
1129 strcat(buf, rfc822timestamp());
1130 strcat(buf, "\r\n");
1131 #endif /* HAVE_SNPRINTF */
1132 n = stuffline(ctl, buf);
1138 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1142 report(stdout, GT_("writing RFC822 msgblk.headers\n"));
1144 free(msgblk.headers);
1145 msgblk.headers = NULL;
1146 free_str_list(&msgblk.recipients);
1149 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1152 /* write error notifications */
1153 if (no_local_matches || has_nuls || bad_addresses)
1156 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1159 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1160 if (no_local_matches)
1162 if (reject_count != 1)
1163 strcat(errhd, GT_("no recipient addresses matched declared local names"));
1166 for (idp = msgblk.recipients; idp; idp = idp->next)
1167 if (idp->val.status.mark == XMIT_REJECT)
1169 sprintf(errhd+strlen(errhd), GT_("recipient address %s didn't match any local name"), idp->id);
1175 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1176 strcat(errhd, "; ");
1177 strcat(errhd, GT_("message has embedded NULs"));
1182 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1183 strcat(errhd, "; ");
1184 strcat(errhd, GT_("SMTP listener rejected local recipient addresses: "));
1185 errlen = strlen(errhd);
1186 for (idp = msgblk.recipients; idp; idp = idp->next)
1187 if (idp->val.status.mark == XMIT_RCPTBAD)
1188 errlen += strlen(idp->id) + 2;
1190 xalloca(errmsg, char *, errlen+3);
1191 (void) strcpy(errmsg, errhd);
1192 for (idp = msgblk.recipients; idp; idp = idp->next)
1193 if (idp->val.status.mark == XMIT_RCPTBAD)
1195 strcat(errmsg, idp->id);
1197 strcat(errmsg, ", ");
1202 strcat(errmsg, "\r\n");
1204 /* ship out the error line */
1205 stuffline(ctl, errmsg);
1208 /* issue the delimiter line */
1213 stuffline(ctl, buf);
1215 /* free(msgblk.headers); */
1216 free_str_list(&msgblk.recipients);
1217 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1220 int readbody(int sock, struct query *ctl, flag forward, int len)
1221 /* read and dispose of a message body presented on sock */
1222 /* ctl: query control record */
1223 /* sock: to which the server is connected */
1224 /* len: length of message */
1225 /* forward: TRUE to forward */
1228 unsigned char buf[MSGBUFSIZE+4];
1229 unsigned char *inbufp = buf;
1230 flag issoftline = FALSE;
1233 * Pass through the text lines in the body.
1235 * Yes, this wants to be ||, not &&. The problem is that in the most
1236 * important delimited protocol, POP3, the length is not reliable.
1237 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1238 * So, for delimited protocols we need to ignore the length here and
1239 * instead drop out of the loop with a break statement when we see
1240 * the message delimiter.
1242 while (protocol->delimited || len > 0)
1244 set_timeout(mytimeout);
1245 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1253 /* write the message size dots */
1256 sizeticker += linelen;
1257 while (sizeticker >= SIZETICKER)
1259 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1264 sizeticker -= SIZETICKER;
1269 /* check for end of message */
1270 if (protocol->delimited && *inbufp == '.')
1272 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1274 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1277 msgblk.msglen--; /* subtract the size of the dot escape */
1280 msgblk.msglen += linelen;
1282 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1283 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1284 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1287 * Soft linebreak, but less than 200 bytes left in
1288 * input buffer. Rather than doing a buffer overrun,
1289 * ignore the soft linebreak, NL-terminate data and
1290 * deliver what we have now.
1291 * (Who writes lines longer than 2K anyway?)
1293 *inbufp = '\n'; *(inbufp+1) = '\0';
1298 /* ship out the text line */
1299 if (forward && (!issoftline))
1304 /* guard against very long lines */
1305 buf[MSGBUFSIZE+1] = '\r';
1306 buf[MSGBUFSIZE+2] = '\n';
1307 buf[MSGBUFSIZE+3] = '\0';
1309 n = stuffline(ctl, buf);
1313 report(stdout, GT_("writing message text\n"));
1317 else if (outlevel >= O_VERBOSE && !isafile(1))
1328 void init_transact(const struct method *proto)
1329 /* initialize state for the send and receive functions */
1332 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1333 protocol = (struct method *)proto;
1336 #if defined(HAVE_STDARG_H)
1337 void gen_send(int sock, const char *fmt, ... )
1339 void gen_send(sock, fmt, va_alist)
1340 int sock; /* socket to which server is connected */
1341 const char *fmt; /* printf-style format */
1344 /* assemble command in printf(3) style and send to the server */
1346 char buf [MSGBUFSIZE+1];
1349 if (protocol->tagged && !suppress_tags)
1350 (void) sprintf(buf, "%s ", GENSYM);
1354 #if defined(HAVE_STDARG_H)
1359 #ifdef HAVE_VSNPRINTF
1360 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1362 vsprintf(buf + strlen(buf), fmt, ap);
1366 #ifdef HAVE_SNPRINTF
1367 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1369 strcat(buf, "\r\n");
1370 #endif /* HAVE_SNPRINTF */
1371 SockWrite(sock, buf, strlen(buf));
1373 if (outlevel >= O_MONITOR)
1377 if (shroud[0] && (cp = strstr(buf, shroud)))
1381 sp = cp + strlen(shroud);
1387 buf[strlen(buf)-2] = '\0';
1388 report(stdout, "%s> %s\n", protocol->name, buf);
1392 int gen_recv(sock, buf, size)
1393 /* get one line of input from the server */
1394 int sock; /* socket to which server is connected */
1395 char *buf; /* buffer to receive input */
1396 int size; /* length of buffer */
1398 int oldphase = phase; /* we don't have to be re-entrant */
1400 phase = SERVER_WAIT;
1401 set_timeout(mytimeout);
1402 if (SockRead(sock, buf, size) == -1)
1411 if (buf[strlen(buf)-1] == '\n')
1412 buf[strlen(buf)-1] = '\0';
1413 if (buf[strlen(buf)-1] == '\r')
1414 buf[strlen(buf)-1] = '\0';
1415 if (outlevel >= O_MONITOR)
1416 report(stdout, "%s< %s\n", protocol->name, buf);
1422 #if defined(HAVE_STDARG_H)
1423 int gen_transact(int sock, const char *fmt, ... )
1425 int gen_transact(int sock, fmt, va_alist)
1426 int sock; /* socket to which server is connected */
1427 const char *fmt; /* printf-style format */
1430 /* assemble command in printf(3) style, send to server, accept a response */
1433 char buf [MSGBUFSIZE+1];
1435 int oldphase = phase; /* we don't have to be re-entrant */
1437 phase = SERVER_WAIT;
1439 if (protocol->tagged && !suppress_tags)
1440 (void) sprintf(buf, "%s ", GENSYM);
1444 #if defined(HAVE_STDARG_H)
1449 #ifdef HAVE_VSNPRINTF
1450 vsnprintf(buf + strlen(buf), sizeof(buf)-strlen(buf), fmt, ap);
1452 vsprintf(buf + strlen(buf), fmt, ap);
1456 #ifdef HAVE_SNPRINTF
1457 snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "\r\n");
1459 strcat(buf, "\r\n");
1460 #endif /* HAVE_SNPRINTF */
1461 SockWrite(sock, buf, strlen(buf));
1463 if (outlevel >= O_MONITOR)
1467 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
1471 sp = cp + strlen(shroud);
1477 buf[strlen(buf)-1] = '\0';
1478 report(stdout, "%s> %s\n", protocol->name, buf);
1481 /* we presume this does its own response echoing */
1482 ok = (protocol->parse_response)(sock, buf);
1488 /* transact.c ends here */