2 * driver.c -- generic driver for mail fetch method protocols
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
14 #if defined(STDC_HEADERS)
17 #if defined(HAVE_UNISTD_H)
20 #if defined(HAVE_STDARG_H)
25 #if defined(HAVE_ALLOCA_H)
28 #if defined(HAVE_SYS_ITIMER_H)
29 #include <sys/itimer.h>
34 #ifdef HAVE_GETHOSTBYNAME
37 #endif /* HAVE_GETHOSTBYNAME */
44 #if defined (__bsdi__)
45 #include <des.h> /* order of includes matters */
47 #define krb_get_err_text(e) (krb_err_txt[e])
51 #endif /* ! defined (__bsdi__) */
52 #include <netinet/in.h>
54 #endif /* KERBEROS_V4 */
55 #include "fetchmail.h"
59 /* BSD portability hack...I know, this is an ugly place to put it */
60 #if !defined(SIGCHLD) && defined(SIGCLD)
61 #define SIGCHLD SIGCLD
64 #define SMTP_PORT 25 /* standard SMTP service port */
66 extern char *strstr(); /* needed on sysV68 R3V7.1. */
68 int fetchlimit; /* how often to tear down the server connection */
69 int batchcount; /* count of messages sent in current batch */
70 flag peek_capable; /* can we peek for better error recovery? */
72 static const struct method *protocol;
73 static jmp_buf restart;
77 #define GENSYM (sprintf(tag, "a%04d", ++tagnum), tag)
79 static char *shroud; /* string to shroud in debug output, if non-NULL */
80 static int mytimeout; /* value of nonreponse timeout */
82 static void set_timeout(int timeleft)
83 /* reset the nonresponse-timeout */
85 struct itimerval ntimeout;
87 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
88 ntimeout.it_value.tv_sec = timeleft;
89 ntimeout.it_value.tv_usec = 0;
90 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
93 static void timeout_handler (int signal)
94 /* handle server-timeout SIGALRM signal */
100 #define XMIT_REJECT 2
101 #define XMIT_ANTISPAM 3
102 static int accept_count, reject_count;
104 #ifdef HAVE_RES_SEARCH
107 static int is_host_alias(const char *name, struct query *ctl)
108 /* determine whether name is a DNS alias of the hostname */
111 struct mxentry *mxp, *mxrecords;
113 struct hostdata *lead_server =
114 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
117 * The first three checks are optimizations that will catch a good
120 * (1) check against the poll name the user specified. Odds are
121 * good this will either be the mailserver's FQDN or a suffix of
122 * it with the mailserver's domain's default host name omitted.
124 * (2) Check the `via' or true host name if present, just in case
125 * the poll name is a label for one of a couple of different
126 * configurations and the real server name is here.
128 * (3) Then check the rest of the `also known as'
129 * cache accumulated by previous DNS checks. This cache is primed
130 * by the aka list option.
132 * (4) Finally check against the mailserver's FQDN, in case
133 * it's not the same as the declared hostname.
135 * Any of these on a mail address is definitive. Only if the
136 * name doesn't match any is it time to call the bind library.
137 * If this happens odds are good we're looking at an MX name.
139 if (str_in_list(&lead_server->names, name))
141 else if (ctl->server.via && strcmp(name, ctl->server.via) == 0)
143 else if (strcmp(name, ctl->server.canonical_name) == 0)
145 else if (!ctl->server.dns)
149 * We know DNS service was up at the beginning of this poll cycle.
150 * If it's down, our nameserver has crashed. We don't want to try
151 * delivering the current message or anything else from this
152 * mailbox until it's back up.
154 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
156 if (strcmp(ctl->server.canonical_name, he->h_name) == 0)
164 case HOST_NOT_FOUND: /* specified host is unknown */
165 case NO_ADDRESS: /* valid, but does not have an IP address */
168 case NO_RECOVERY: /* non-recoverable name server error */
169 case TRY_AGAIN: /* temporary error on authoritative server */
171 if (outlevel != O_SILENT)
172 putchar('\n'); /* terminate the progress message */
174 "nameserver failure while looking for `%s' during poll of %s.",
175 name, ctl->server.names->id);
181 * We're only here if DNS was OK but the gethostbyname() failed
182 * with a HOST_NOT_FOUND or NO_ADDRESS error.
183 * Search for a name match on MX records pointing to the server.
186 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
190 case HOST_NOT_FOUND: /* specified host is unknown */
191 case NO_ADDRESS: /* valid, but does not have an IP address */
195 case NO_RECOVERY: /* non-recoverable name server error */
196 case TRY_AGAIN: /* temporary error on authoritative server */
199 "nameserver failure while looking for `%s' during poll of %s.",
200 name, ctl->server.names->id);
207 for (mxp = mxrecords; mxp->name; mxp++)
208 if (strcmp(ctl->server.canonical_name, mxp->name) == 0)
214 /* add this name to relevant server's `also known as' list */
215 save_str(&lead_server->names, -1, name);
219 static void map_name(name, ctl, xmit_names)
220 /* add given name to xmit_names if it matches declared localnames */
221 const char *name; /* name to map */
222 struct query *ctl; /* list of permissible aliases */
223 struct idlist **xmit_names; /* list of recipient names parsed out */
227 lname = idpair_find(&ctl->localnames, name);
228 if (!lname && ctl->wildcard)
231 if (lname != (char *)NULL)
233 if (outlevel == O_VERBOSE)
234 error(0, 0, "mapped %s to local %s", name, lname);
235 save_str(xmit_names, XMIT_ACCEPT, lname);
240 void find_server_names(hdr, ctl, xmit_names)
241 /* parse names out of a RFC822 header into an ID list */
242 const char *hdr; /* RFC822 header in question */
243 struct query *ctl; /* list of permissible aliases */
244 struct idlist **xmit_names; /* list of recipient names parsed out */
246 if (hdr == (char *)NULL)
252 if ((cp = nxtaddr(hdr)) != (char *)NULL)
256 if ((atsign = strchr(cp, '@')))
261 * Does a trailing segment of the hostname match something
262 * on the localdomains list? If so, save the whole name
265 for (idp = ctl->server.localdomains; idp; idp = idp->next)
269 rhs = atsign + (strlen(atsign) - strlen(idp->id));
270 if ((rhs[-1] == '.' || rhs[-1] == '@')
271 && strcasecmp(rhs, idp->id) == 0)
273 if (outlevel == O_VERBOSE)
274 error(0, 0, "passed through %s matching %s",
276 save_str(xmit_names, XMIT_ACCEPT, cp);
283 * Check to see if the right-hand part is an alias
284 * or MX equivalent of the mailserver. If it's
285 * not, skip this name. If it is, we'll keep
286 * going and try to find a mapping to a client name.
288 if (!is_host_alias(atsign+1, ctl))
290 save_str(xmit_names, XMIT_REJECT, cp);
297 map_name(cp, ctl, xmit_names);
299 ((cp = nxtaddr((char *)NULL)) != (char *)NULL);
303 char *parse_received(struct query *ctl, char *bufp)
304 /* try to extract real addressee from the Received line */
307 static char rbuf[HOSTLEN + USERNAMELEN + 4];
310 * Try to extract the real envelope addressee. We look here
311 * specifically for the mailserver's Received line.
312 * Note: this will only work for sendmail, or an MTA that
313 * shares sendmail's convention for embedding the envelope
314 * address in the Received line. Sendmail itself only
315 * does this when the mail has a single recipient.
317 if ((ok = strstr(bufp, "by ")) == (char *)NULL)
323 /* extract space-delimited token after "by " */
324 for (sp = ok + 3; isspace(*sp); sp++)
327 for (; !isspace(*sp); sp++)
332 * If it's a DNS name of the mail server, look for the
333 * recipient name after a following "for". Otherwise
336 if (is_host_alias(rbuf, ctl))
337 ok = strstr(sp, "for ");
350 while (*sp && *sp != '>' && *sp != '@' && *sp != ';')
355 /* uh oh -- whitespace here can't be right! */
366 if (outlevel == O_VERBOSE)
367 error(0, 0, "found Received address `%s'", rbuf);
371 #endif /* HAVE_RES_SEARCH */
373 int smtp_open(struct query *ctl)
374 /* try to open a socket to the appropriate SMTP server for this query */
378 /* maybe it's time to close the socket in order to force delivery */
379 if (ctl->batchlimit > 0 && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
381 close(ctl->smtp_socket);
382 ctl->smtp_socket = -1;
386 /* run down the SMTP hunt list looking for a server that's up */
387 for (idp = ctl->smtphunt; idp; idp = idp->next)
390 * RFC 1123 requires that the domain name in HELO address is a
391 * "valid principal domain name" for the client host. We
392 * violate this with malice aforethought in order to make the
393 * Received headers and logging look right.
395 * In fact this code relies on the RFC1123 requirement that the
396 * SMTP listener must accept messages even if verification of the
397 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
400 /* if no socket to this host is already set up, try to open ESMTP */
401 if (ctl->smtp_socket == -1)
403 #ifndef HAVE_RES_SEARCH
405 #endif /* HAVE_RES_SEARCH */
407 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
410 #ifndef HAVE_RES_SEARCH
412 * How we compute the fake client name to pass to the
413 * listener doesn't affect behavior on RFC1123- violating
414 * listener that check for name match; we're going to lose
415 * on those anyway because we can never give them a name
416 * that matches the local machine fetchmail is running on.
417 * What it will affect is the listener's logging.
419 * If we have the mailserver's canonical FQDN that is clearly
420 * the right thing to log. If we don't life is more complicated.
421 * The problem is there are two clashing cases:
423 * (1) The poll name is a label. In that case we want the
424 * log to show the via or true mailserver name.
426 * (2) The poll name is the true one, the via name is localhost.
427 * This is going to be typical for ssh-using configurations.
429 * We're going to assume the via name is true unless it's
432 if (ctrl->server.via && strcmp(ctrl->server.via, "localhost"))
433 fakename = ctrl->server.via;
435 fakename = ctrl->server->names.id;
436 #endif /* HAVE_RES_SEARCH */
438 if (SMTP_ok(ctl->smtp_socket) != SM_OK
439 || SMTP_ehlo(ctl->smtp_socket,
440 #ifdef HAVE_RES_SEARCH
441 ctl->server.canonical_name,
444 #endif /* HAVE_RES_SEARCH */
445 &ctl->server.esmtp_options) != SM_OK)
448 * RFC 1869 warns that some listeners hang up on a failed EHLO,
449 * so it's safest not to assume the socket will still be good.
451 close(ctl->smtp_socket);
452 ctl->smtp_socket = -1;
456 ctl->smtphost = idp->id;
461 /* if opening for ESMTP failed, try SMTP */
462 if (ctl->smtp_socket == -1)
464 if ((ctl->smtp_socket = SockOpen(idp->id,SMTP_PORT)) == -1)
466 else if (SMTP_ok(ctl->smtp_socket) != SM_OK
467 || SMTP_helo(ctl->smtp_socket,
468 #ifdef HAVE_RES_SEARCH
469 ctl->server.canonical_name
472 #endif /* HAVE_RES_SEARCH */
475 close(ctl->smtp_socket);
476 ctl->smtp_socket = -1;
480 ctl->smtphost = idp->id;
486 return(ctl->smtp_socket);
489 /* these are shared by readheaders and readbody */
491 static RETSIGTYPE (*sigchld)();
492 static int sizeticker;
494 static int readheaders(sock, len, ctl, realname)
495 /* read message headers and ship to SMTP or MDA */
496 int sock; /* to which the server is connected */
497 long len; /* length of message */
498 struct query *ctl; /* query control record */
499 char *realname; /* real name of host */
501 char buf[MSGBUFSIZE+1], return_path[MSGBUFSIZE+1];
502 int from_offs, ctt_offs, env_offs, addressoffs[128], next_address;
503 char *headers, *received_for;
504 int n, linelen, oldlen, ch, remaining;
506 struct idlist *idp, *xmit_names;
507 flag good_addresses, bad_addresses, has_nuls;
508 #ifdef HAVE_RES_SEARCH
509 flag no_local_matches = FALSE;
510 #endif /* HAVE_RES_SEARCH */
513 next_address = sizeticker = 0;
515 return_path[0] = '\0';
516 olderrs = ctl->errcount;
518 /* read message headers */
519 headers = received_for = NULL;
520 from_offs = ctt_offs = env_offs = -1;
522 for (remaining = len; remaining > 0; remaining -= linelen)
526 line = xmalloc(sizeof(buf));
530 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1)
534 /* lines may not be properly CRLF terminated; fix this for qmail */
537 cp = buf + strlen(buf) - 1;
538 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
546 set_timeout(ctl->server.timeout);
547 /* leave extra room for reply_hack to play with */
548 line = (char *) realloc(line, strlen(line) + strlen(buf) + HOSTLEN + 1);
550 if (line[0] == '\r' && line[1] == '\n')
553 /* we may need to grab RFC822 continuations */
554 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
556 /* write the message size dots */
557 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
559 sizeticker += linelen;
560 while (sizeticker >= SIZETICKER)
563 sizeticker -= SIZETICKER;
567 if (linelen != strlen(line))
570 /* check for end of headers; don't save terminating line */
571 if (line[0] == '\r' && line[1] == '\n')
578 * This code prevents fetchmail from becoming an accessory after
579 * the fact to upstream sendmails with the `E' option on. This
580 * can result in an escaped Unix From_ line at the beginning of
581 * the headers. If fetchmail just passes it through, the client
582 * listener may think the message has *no* headers (since the first)
583 * line it sees doesn't look RFC822-conformant) and fake up a set.
585 * What the user would see in this case is bogus (synthesized)
586 * headers, followed by a blank line, followed by the >From,
587 * followed by the real headers, followed by a blank line,
590 * We forestall this lossage by tossing anything that looks
591 * like an escaped From_ line in headers. These aren't RFC822
592 * so our conscience is clear...
594 if (!strncasecmp(line, ">From ", 6))
601 * If we see a Status line, it may have been inserted by an MUA
602 * on the mail host, or it may have been inserted by the server
603 * program after the headers in the transaction stream. This
604 * can actually hose some new-mail notifiers such as xbuffy,
605 * which assumes any Status line came from a *local* MDA and
606 * therefore indicates that the message has been seen.
608 * Some buggy POP servers (including at least the 3.3(20)
609 * version of the one distributed with IMAP) insert empty
610 * Status lines in the transaction stream; we'll chuck those
611 * unconditionally. Nonempty ones get chucked if the user
612 * turns on the dropstatus flag.
614 if (!strncasecmp(line, "Status:", 7))
618 for (cp = line + 7; *cp && isspace(*cp); cp++)
621 if (!*cp || ctl->dropstatus)
629 * OK, this is messy. If we're forwarding by SMTP, it's the
630 * SMTP-receiver's job (according to RFC821, page 22, section
631 * 4.1.1) to generate a Return-Path line on final delivery.
632 * The trouble is, we've already got one because the
633 * mailserver's SMTP thought *it* was responsible for final
636 * Stash away the contents of Return-Path for use in generating
637 * MAIL FROM later on, then prevent the header from being saved
638 * with the others. In effect, we strip it off here.
640 * If the SMTP server conforms to the standards, and fetchmail gets the
641 * envelope sender from the Return-Path, the new Return-Path should be
642 * exactly the same as the original one.
644 if (!ctl->mda && !strncasecmp("Return-Path:", line, 12))
646 strcpy(return_path, nxtaddr(line));
652 reply_hack(line, realname);
656 oldlen = strlen(line);
657 headers = xmalloc(oldlen + 1);
658 (void) strcpy(headers, line);
666 newlen = oldlen + strlen(line);
667 headers = (char *) realloc(headers, newlen + 1);
670 strcpy(headers + oldlen, line);
672 line = headers + oldlen;
676 if (from_offs == -1 && !strncasecmp("From:", line, 5))
677 from_offs = (line - headers);
678 else if (from_offs == -1 && !strncasecmp("Resent-From:", line, 12))
679 from_offs = (line - headers);
680 else if (from_offs == -1 && !strncasecmp("Apparently-From:", line, 16))
681 from_offs = (line - headers);
683 else if (ctl->server.envelope != STRING_DISABLED && env_offs == -1
684 && !strncasecmp(ctl->server.envelope,
686 strlen(ctl->server.envelope)))
687 env_offs = (line - headers);
689 else if (!strncasecmp("To:", line, 3))
691 if (next_address >= sizeof(addressoffs)/sizeof(addressoffs[0]))
692 error(PS_UNDEFINED, errno, "too many destination headers");
693 addressoffs[next_address++] = (line - headers);
696 else if (!strncasecmp("Cc:", line, 3))
698 if (next_address >= sizeof(addressoffs)/sizeof(addressoffs[0]))
699 error(PS_UNDEFINED, errno, "too many destination headers");
700 addressoffs[next_address++] = (line - headers);
703 else if (!strncasecmp("Bcc:", line, 4))
705 if (next_address >= sizeof(addressoffs)/sizeof(addressoffs[0]))
706 error(PS_UNDEFINED, errno, "too many destination headers");
707 addressoffs[next_address++] = (line - headers);
710 else if (!strncasecmp("Content-Transfer-Encoding:", line, 26))
711 ctt_offs = (line - headers);
713 #ifdef HAVE_RES_SEARCH
715 * The `no envelope' option should also disable parsing of Received
718 else if (MULTIDROP(ctl) && ctl->server.envelope != STRING_DISABLED && !received_for && !strncasecmp("Received:", line, 9))
719 received_for = parse_received(ctl, line);
720 #endif /* HAVE_RES_SEARCH */
724 * Hack time. If the first line of the message was blank, with no headers
725 * (this happens occasionally due to bad gatewaying software) cons up
726 * a set of fake headers.
728 * If you modify the fake header template below, be sure you don't
729 * make either From or To address @-less, otherwise the reply_hack
730 * logic will do bad things.
732 if (headers == (char *)NULL)
735 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
736 fetchmailhost, user, ctl->remotename, realname);
737 headers = xstrdup(buf);
741 * We can now process message headers before reading the text.
742 * In fact we have to, as this will tell us where to forward to.
745 /* cons up a list of local recipients */
746 xmit_names = (struct idlist *)NULL;
747 bad_addresses = good_addresses = accept_count = reject_count = 0;
748 #ifdef HAVE_RES_SEARCH
749 /* is this a multidrop box? */
752 if (env_offs > -1) /* We have the actual envelope addressee */
753 find_server_names(headers + env_offs, ctl, &xmit_names);
754 else if (received_for)
756 * We have the Received for addressee.
757 * It has to be a mailserver address, or we
758 * wouldn't have got here.
760 map_name(received_for, ctl, &xmit_names);
766 * We haven't extracted the envelope address.
767 * So check all the header addresses.
769 for (i = 0; i < next_address; i++)
770 find_server_names(headers + addressoffs[i], ctl, &xmit_names);
774 no_local_matches = TRUE;
775 save_str(&xmit_names, XMIT_ACCEPT, user);
776 if (outlevel == O_VERBOSE)
778 "no local matches, forwarding to %s",
782 else /* it's a single-drop box, use first localname */
783 #endif /* HAVE_RES_SEARCH */
784 save_str(&xmit_names, XMIT_ACCEPT, ctl->localnames->id);
788 * Time to either address the message or decide we can't deliver it yet.
790 if (ctl->errcount > olderrs) /* there were DNS errors above */
792 if (outlevel == O_VERBOSE)
793 error(0,0, "forwarding and deletion suppressed due to DNS errors");
795 return(PS_TRANSIENT);
797 else if (ctl->mda) /* we have a declared MDA */
803 * We go through this in order to be able to handle very
804 * long lists of users and (re)implement %s.
806 for (idp = xmit_names; idp; idp = idp->next)
807 if (idp->val.num == XMIT_ACCEPT)
808 length += (strlen(idp->id) + 1);
809 names = (char *)alloca(length);
811 for (idp = xmit_names; idp; idp = idp->next)
812 if (idp->val.num == XMIT_ACCEPT)
814 strcat(names, idp->id);
817 cmd = (char *)alloca(strlen(ctl->mda) + length);
818 sprintf(cmd, ctl->mda, names);
819 if (outlevel == O_VERBOSE)
820 error(0, 0, "about to deliver with: %s", cmd);
824 * Arrange to run with user's permissions if we're root.
825 * This will initialize the ownership of any files the
826 * MDA creates properly. (The seteuid call is available
827 * under all BSDs and Linux)
830 #endif /* HAVE_SETEUID */
832 sinkfp = popen(cmd, "w");
835 /* this will fail quietly if we didn't start as root */
837 #endif /* HAVE_SETEUID */
841 error(0, -1, "MDA open failed");
845 sigchld = signal(SIGCHLD, SIG_DFL);
849 char *ap, *ctt, options[MSGBUFSIZE];
851 /* build a connection to the SMTP listener */
852 if ((smtp_open(ctl) == -1))
854 free_str_list(&xmit_names);
855 error(0, -1, "SMTP connect to %s failed",
856 ctl->smtphost ? ctl->smtphost : "localhost");
861 * Compute ESMTP options. It's a kluge to use nxtaddr()
862 * here because the contents of the Content-Transfer-Encoding
863 * headers isn't semantically an address. But it has the
864 * desired tokenizing effect.
867 if (ctl->server.esmtp_options & ESMTP_8BITMIME)
869 sprintf(options, " BODY=8BITMIME");
870 else if ((ctt_offs >= 0) && (ctt = nxtaddr(headers + ctt_offs)))
872 if (!strcasecmp(ctt,"7BIT"))
873 sprintf(options, " BODY=7BIT");
874 else if (!strcasecmp(ctt,"8BIT"))
875 sprintf(options, " BODY=8BITMIME");
877 if ((ctl->server.esmtp_options & ESMTP_SIZE))
878 sprintf(options + strlen(options), " SIZE=%ld", len);
881 * If there is a Return-Path address on the message, this was
882 * almost certainly the MAIL FROM address given the originating
883 * sendmail. This is the best thing to use for logging the
884 * message origin (it sets up the right behavior for bounces and
885 * mailing lists). Otherwise, take the From address.
887 * Try to get the SMTP listener to take the Return-Path or
888 * From address as MAIL FROM . If it won't, fall back on the
889 * calling-user ID. This won't affect replies, which use the
890 * header From address anyway.
892 * RFC 1123 requires that the domain name part of the
893 * MAIL FROM address be "canonicalized", that is a
894 * FQDN or MX but not a CNAME. We'll assume the From
895 * header is already in this form here (it certainly
896 * is if rewrite is on). RFC 1123 is silent on whether
897 * a nonexistent hostname part is considered canonical.
899 * This is a potential problem if the MTAs further upstream
900 * didn't pass canonicalized From/Return-Path lines, *and* the
901 * local SMTP listener insists on them.
906 else if (from_offs == -1 || !(ap = nxtaddr(headers + from_offs)))
908 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
910 int smtperr = atoi(smtp_response);
913 * Suppress error message only if the response specifically
914 * means `excluded for policy reasons'. We *should* see
915 * an error when the return code is less specific.
917 if (smtperr >= 400 && smtperr != 571)
918 error(0, -1, "SMTP error: %s", smtp_response);
922 case 571: /* sendmail's "unsolicited email refused" */
923 case 501: /* exim's old antispam response */
924 case 550: /* exim's new antispam response (temporary) */
926 * SMTP listener explicitly refuses to deliver
927 * mail coming from this address, probably due
928 * to an anti-spam domain exclusion. Respect
929 * this. Don't try to ship the message, and
930 * don't prevent it from being deleted.
935 case 452: /* insufficient system storage */
937 * Temporary out-of-queue-space condition on the
938 * ESMTP server. Don't try to ship the message,
939 * and suppress deletion so it can be retried on
940 * a future retrieval cycle.
942 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
944 return(PS_TRANSIENT);
946 case 552: /* message exceeds fixed maximum message size */
948 * Permanent no-go condition on the
949 * ESMTP server. Don't try to ship the message,
950 * and allow it to be deleted.
952 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
956 default: /* retry with invoking user's address */
957 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
959 error(0, -1, "SMTP error: %s", smtp_response);
961 return(PS_SMTP); /* should never happen */
967 * Now list the recipient addressees
969 * RFC 1123 requires that the domain name part of the
970 * RCPT TO address be "canonicalized", that is a FQDN
971 * or MX but not a CNAME. RFC1123 doesn't say whether
972 * the FQDN part can be null (as it frequently will be
973 * here), but it's hard to see how this could cause a
976 for (idp = xmit_names; idp; idp = idp->next)
977 if (idp->val.num == XMIT_ACCEPT)
978 if (SMTP_rcpt(ctl->smtp_socket, idp->id) == SM_OK)
983 idp->val.num = XMIT_ANTISPAM;
985 "SMTP listener doesn't like recipient address `%s'", idp->id);
987 if (!good_addresses && SMTP_rcpt(ctl->smtp_socket, user) != SM_OK)
990 "can't even send to calling user!");
995 /* tell it we're ready to send data */
996 SMTP_data(ctl->smtp_socket);
999 /* we may need to strip carriage returns */
1004 for (sp = tp = headers; *sp; sp++)
1011 /* write all the headers */
1013 if (ctl->mda && sinkfp)
1014 n = fwrite(headers, 1, strlen(headers), sinkfp);
1015 else if (ctl->smtp_socket != -1)
1016 n = SockWrite(ctl->smtp_socket, headers, strlen(headers));
1021 error(0, errno, "writing RFC822 headers");
1025 signal(SIGCHLD, sigchld);
1029 else if (outlevel == O_VERBOSE)
1032 /* write error notifications */
1033 #ifdef HAVE_RES_SEARCH
1034 if (no_local_matches || has_nuls || bad_addresses)
1036 if (has_nuls || bad_addresses)
1037 #endif /* HAVE_RES_SEARCH */
1040 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1043 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1044 #ifdef HAVE_RES_SEARCH
1045 if (no_local_matches)
1047 if (reject_count != 1)
1048 strcat(errhd, "no recipient addresses matched declared local names");
1051 for (idp = xmit_names; idp; idp = idp->next)
1052 if (idp->val.num == XMIT_REJECT)
1054 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1057 #endif /* HAVE_RES_SEARCH */
1061 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1062 strcat(errhd, "; ");
1063 strcat(errhd, "message has embedded NULs");
1068 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1069 strcat(errhd, "; ");
1070 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1071 errlen = strlen(errhd);
1072 for (idp = xmit_names; idp; idp = idp->next)
1073 if (idp->val.num == XMIT_ANTISPAM)
1074 errlen += strlen(idp->id) + 2;
1076 errmsg = alloca(errlen+3);
1077 (void) strcpy(errmsg, errhd);
1078 for (idp = xmit_names; idp; idp = idp->next)
1079 if (idp->val.num == XMIT_ANTISPAM)
1081 strcat(errmsg, idp->id);
1083 strcat(errmsg, ", ");
1088 if (ctl->mda && !ctl->forcecr)
1089 strcat(errmsg, "\n");
1091 strcat(errmsg, "\r\n");
1093 /* we may need to strip carriage returns */
1098 for (sp = tp = errmsg; *sp; sp++)
1104 /* ship out the error line */
1108 fwrite(errmsg, sizeof(char), strlen(errmsg), sinkfp);
1110 SockWrite(ctl->smtp_socket, errmsg, strlen(errmsg));
1114 free_str_list(&xmit_names);
1116 /* issue the delimiter line */
1117 if (sinkfp && ctl->mda)
1118 fputc('\n', sinkfp);
1119 else if (ctl->smtp_socket != -1)
1122 SockWrite(ctl->smtp_socket, "\n", 1);
1124 SockWrite(ctl->smtp_socket, "\r\n", 2);
1130 static int readbody(sock, ctl, forward, len, delimited)
1131 /* read and dispose of a message body presented on sock */
1132 struct query *ctl; /* query control record */
1133 int sock; /* to which the server is connected */
1134 int len; /* length of message */
1135 flag forward; /* TRUE to forward */
1136 flag delimited; /* does the protocol use a message delimiter? */
1139 char buf[MSGBUFSIZE+1], *cp;
1141 /* pass through the text lines */
1142 while (delimited || len > 0)
1144 if ((linelen = SockRead(sock, buf, sizeof(buf)-1)) == -1)
1146 set_timeout(ctl->server.timeout);
1148 /* write the message size dots */
1151 sizeticker += linelen;
1152 while (sizeticker >= SIZETICKER)
1154 if (outlevel > O_SILENT)
1156 sizeticker -= SIZETICKER;
1161 /* fix messages that have only \n line-termination (for qmail) */
1164 cp = buf + strlen(buf) - 1;
1165 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
1173 /* check for end of message */
1174 if (delimited && *buf == '.')
1175 if (buf[1] == '\r' && buf[2] == '\n')
1178 /* ship out the text line */
1184 * SMTP byte-stuffing. We only do this if the protocol does *not*
1185 * use .<CR><LF> as EOM. If it does, the server will already have
1186 * decorated any . lines it sends back up.
1188 if (!delimited && *buf == '.')
1189 if (sinkfp && ctl->mda)
1191 else if (ctl->smtp_socket != -1)
1192 SockWrite(ctl->smtp_socket, buf, 1);
1194 /* we may need to strip carriage returns */
1199 for (sp = tp = buf; *sp; sp++)
1207 n = fwrite(buf, 1, strlen(buf), sinkfp);
1208 else if (ctl->smtp_socket != -1)
1209 n = SockWrite(ctl->smtp_socket, buf, strlen(buf));
1213 error(0, errno, "writing message text");
1217 signal(SIGCHLD, sigchld);
1221 else if (outlevel == O_VERBOSE)
1231 kerberos_auth (socket, canonical)
1232 /* authenticate to the server host using Kerberos V4 */
1233 int socket; /* socket to server host */
1234 const char *canonical; /* server name */
1236 char * host_primary;
1240 Key_schedule schedule;
1243 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1244 rem = (krb_sendauth (0L, socket, ticket, "pop",
1246 ((char *) (krb_realmofhost (canonical))),
1247 ((unsigned long) 0),
1251 ((struct sockaddr_in *) 0),
1252 ((struct sockaddr_in *) 0),
1255 if (rem != KSUCCESS)
1257 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1262 #endif /* KERBEROS_V4 */
1264 int do_protocol(ctl, proto)
1265 /* retrieve messages from server using given protocol method table */
1266 struct query *ctl; /* parsed options with merged-in defaults */
1267 const struct method *proto; /* protocol method table */
1269 int ok, js, pst, sock = -1;
1270 char *msg, *cp, realname[HOSTLEN];
1274 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1276 error(0, -1, "Kerberos V4 support not linked.");
1279 #endif /* KERBEROS_V4 */
1281 /* lacking methods, there are some options that may fail */
1284 /* check for unsupported options */
1287 "Option --flush is not supported with %s",
1291 else if (ctl->fetchall) {
1293 "Option --all is not supported with %s",
1298 if (!proto->getsizes && ctl->limit)
1301 "Option --limit is not supported with %s",
1308 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1310 error_init(poll_interval == 0 && !logfile);
1312 /* set up the server-nonresponse timeout */
1313 sigsave = signal(SIGALRM, timeout_handler);
1314 set_timeout(mytimeout = ctl->server.timeout);
1316 if ((js = setjmp(restart)) == 1)
1319 "timeout after %d seconds waiting for %s.",
1320 ctl->server.timeout, ctl->server.names->id);
1321 if (ctl->smtp_socket != -1)
1322 close(ctl->smtp_socket);
1329 char buf [POPBUFSIZE+1], *sp, *realhost;
1330 int *msgsizes, len, num, count, new, deletions = 0;
1334 /* execute pre-initialization command, if any */
1335 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1337 sprintf(buf, "pre-connection command failed with status %d", ok);
1343 /* open a socket to the mail server */
1344 port = ctl->server.port ? ctl->server.port : protocol->port;
1345 realhost = ctl->server.via ? ctl->server.via : ctl->server.names->id;
1346 if ((sock = SockOpen(realhost, port)) == -1)
1348 #ifndef EHOSTUNREACH
1349 #define EHOSTUNREACH (-1)
1351 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1353 error_build("fetchmail: %s connection to %s failed: ",
1354 protocol->name, ctl->server.names->id);
1355 if (h_errno == HOST_NOT_FOUND)
1356 error_complete(0, 0, "host is unknown");
1357 else if (h_errno == NO_ADDRESS)
1358 error_complete(0, 0, "name is valid but has no IP address");
1359 else if (h_errno == NO_RECOVERY)
1360 error_complete(0, 0, "unrecoverable name server error");
1361 else if (h_errno == TRY_AGAIN)
1362 error_complete(0, 0, "temporary name server error");
1364 error_complete(0, 0, "unknown DNS error %d", h_errno);
1366 error_complete(0, errno, "local error");
1373 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1375 ok = kerberos_auth(sock, ctl->server.canonical_name);
1378 set_timeout(ctl->server.timeout);
1380 #endif /* KERBEROS_V4 */
1382 /* accept greeting message from mail server */
1383 ok = (protocol->parse_response)(sock, buf);
1386 set_timeout(ctl->server.timeout);
1389 * Try to parse the host's actual name out of the greeting
1390 * message. We do this so that the progress messages will
1391 * make sense even if the connection is indirected through
1392 * ssh. *Do* use this for hacking reply headers, but *don't*
1393 * use it for error logging, as the names in the log should
1394 * correlate directly back to rc file entries.
1396 * This assumes that the first space-delimited token found
1397 * that contains at least two dots (with the characters on
1398 * each side of the dot alphanumeric to exclude version
1399 * numbers) is the hostname. The hostname candidate may not
1400 * contain @ -- if it does it's probably a mailserver
1401 * maintainer's name. If no such token is found, fall back on
1402 * the .fetchmailrc id.
1405 sp = (char *)NULL; /* sacrifice to -Wall */
1406 for (cp = buf; *cp; cp++)
1410 case 0: /* skip to end of current token */
1415 case 1: /* look for blank-delimited token */
1423 case 2: /* look for first dot */
1426 else if (*cp == ' ')
1428 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1432 case 3: /* look for second dot */
1435 else if (*cp == ' ')
1437 else if (*cp == '.' && isalpha(cp[1]) && isalpha(cp[-1]))
1441 case 4: /* look for trailing space */
1444 else if (*cp == ' ')
1455 char *tp = realname;
1462 strcpy(realname, ctl->server.names->id);
1464 /* try to get authorized to fetch mail */
1465 if (protocol->getauth)
1467 shroud = ctl->password;
1468 ok = (protocol->getauth)(sock, ctl, buf);
1469 shroud = (char *)NULL;
1472 if (ok == PS_LOCKBUSY)
1473 error(0, -1, "Lock-busy error on %s@%s",
1480 error(0, -1, "Authorization failure on %s@%s",
1486 set_timeout(ctl->server.timeout);
1489 ctl->errcount = fetches = 0;
1491 /* now iterate over each folder selected */
1492 for (idp = ctl->mailboxes; idp; idp = idp->next)
1494 if (outlevel >= O_VERBOSE)
1496 error(0, 0, "selecting folder %s");
1498 error(0, 0, "selecting default folder");
1500 /* compute number of messages and number of new messages waiting */
1501 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new);
1504 set_timeout(ctl->server.timeout);
1506 /* show user how many messages we downloaded */
1508 (void) sprintf(buf, "%s@%s:%s",
1509 ctl->remotename, realname, idp->id);
1511 (void) sprintf(buf, "%s@%s", ctl->remotename, realname);
1512 if (outlevel > O_SILENT)
1513 if (count == -1) /* only used for ETRN */
1514 error(0, 0, "Polling %s", buf);
1515 else if (count == 0)
1516 error(0, 0, "No mail at %s", buf);
1519 if (new != -1 && (count - new) > 0)
1520 error(0, 0, "%d message%s (%d seen) at %s.",
1521 count, count > 1 ? "s" : "", count-new, buf);
1523 error(0, 0, "%d message%s at %s.",
1524 count, count > 1 ? "s" : "", buf);
1529 if (new == -1 || ctl->fetchall)
1531 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1536 flag force_retrieval;
1539 * What forces this code is that in POP3 and IMAP2BIS you can't
1540 * fetch a message without having it marked `seen'. In IMAP4,
1541 * on the other hand, you can (peek_capable is set to convey
1544 * The result of being unable to peek is that if there's
1545 * any kind of transient error (DNS lookup failure, or
1546 * sendmail refusing delivery due to process-table limits)
1547 * the message will be marked "seen" on the server without
1548 * having been delivered. This is not a big problem if
1549 * fetchmail is running in foreground, because the user
1550 * will see a "skipped" message when it next runs and get
1553 * But in daemon mode this leads to the message being silently
1554 * ignored forever. This is not acceptable.
1556 * We compensate for this by checking the error count from the
1557 * previous pass and forcing all messages to be considered new
1560 force_retrieval = !peek_capable && (ctl->errcount > 0);
1563 * We may need to get sizes in order to check message
1564 * limits. Or it may be forced because the fetch methods
1565 * don't return reliable sizes.
1567 msgsizes = (int *)NULL;
1568 if (proto->getsizes && (proto->force_getsizes || ctl->limit > 0))
1570 msgsizes = (int *)alloca(sizeof(int) * count);
1572 ok = (proto->getsizes)(sock, count, msgsizes);
1575 set_timeout(ctl->server.timeout);
1578 /* read, forward, and delete messages */
1579 for (num = 1; num <= count; num++)
1581 flag toolarge = (ctl->limit > 0)
1582 && msgsizes && (msgsizes[num-1] > ctl->limit);
1583 flag fetch_it = !toolarge
1584 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
1585 flag suppress_delete = FALSE;
1586 flag suppress_forward = FALSE;
1588 /* we may want to reject this message if it's old */
1591 if (outlevel > O_SILENT)
1593 error_build("skipping message %d", num);
1595 error_build(" (oversized, %d bytes)", msgsizes[num-1]);
1600 flag wholesize = !protocol->fetch_body;
1602 /* request a message */
1603 ok = (protocol->fetch_headers)(sock, ctl, num, &len);
1606 set_timeout(ctl->server.timeout);
1608 /* -1 means we didn't see a size in the response */
1609 if (len == -1 && msgsizes)
1611 len = msgsizes[num - 1];
1615 if (outlevel > O_SILENT)
1617 error_build("reading message %d of %d",num,count);
1620 error_build(" (%d %sbytes)",
1621 len, wholesize ? "" : "header ");
1622 if (outlevel == O_VERBOSE)
1623 error_complete(0, 0, "");
1629 * Read the message headers and ship them to the
1632 ok = readheaders(sock, len, ctl, realname);
1633 if (ok == PS_TRANSIENT)
1634 suppress_delete = TRUE;
1635 else if (ok == PS_REFUSED)
1636 suppress_forward = TRUE;
1639 set_timeout(ctl->server.timeout);
1642 * If we're using IMAP4 or something else that
1643 * can fetch headers separately from bodies,
1644 * it's time to request the body now. This
1645 * fetch may be skipped if we got an anti-spam
1646 * or other PS_REFUSED error response during
1649 if (protocol->fetch_body)
1651 if ((ok = (protocol->trail)(sock, ctl, num)))
1653 set_timeout(ctl->server.timeout);
1655 if (!suppress_forward)
1657 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1659 if (outlevel > O_SILENT && !msgsizes)
1660 error_build(" (%d body bytes) ", len);
1661 set_timeout(ctl->server.timeout);
1665 /* process the body now */
1672 protocol->delimited);
1673 if (ok == PS_TRANSIENT)
1674 suppress_delete = TRUE;
1677 set_timeout(ctl->server.timeout);
1679 /* tell server we got it OK and resynchronize */
1680 if (protocol->trail)
1682 ok = (protocol->trail)(sock, ctl, num);
1685 set_timeout(ctl->server.timeout);
1689 /* end-of-message processing starts here */
1690 if (outlevel == O_VERBOSE)
1691 fputc('\n', stderr);
1697 /* close the delivery pipe, we'll reopen before next message */
1698 rc = pclose(sinkfp);
1699 signal(SIGCHLD, sigchld);
1702 error(0, -1, "MDA exited abnormally or returned nonzero status");
1706 else if (!suppress_forward)
1708 /* write message terminator */
1709 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
1711 error(0, -1, "SMTP listener refused delivery");
1713 suppress_delete = TRUE;
1721 * At this point in flow of control, either we've bombed
1722 * on a protocol error or had delivery refused by the SMTP
1723 * server (unlikely -- I've never seen it) or we've seen
1724 * `accepted for delivery' and the message is shipped.
1725 * It's safe to mark the message seen and delete it on the
1729 /* maybe we delete this message now? */
1730 if (protocol->delete
1732 && (fetch_it ? !ctl->keep : ctl->flush))
1735 if (outlevel > O_SILENT)
1736 error_complete(0, 0, " flushed");
1737 ok = (protocol->delete)(sock, ctl, num);
1740 set_timeout(ctl->server.timeout);
1741 delete_str(&ctl->newsaved, num);
1743 else if (outlevel > O_SILENT)
1744 error_complete(0, 0, " not flushed");
1746 /* perhaps this as many as we're ready to handle */
1747 if (ctl->fetchlimit > 0 && ctl->fetchlimit <= fetches)
1754 set_timeout(ctl->server.timeout);
1755 ok = gen_transact(sock, protocol->exit_cmd);
1757 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
1763 set_timeout(ctl->server.timeout);
1764 if (ok != 0 && ok != PS_SOCKET)
1765 gen_transact(sock, protocol->exit_cmd);
1770 msg = (char *)NULL; /* sacrifice to -Wall */
1777 msg = "authorization";
1780 msg = "missing or bad RFC822 header";
1786 msg = "client/server synchronization";
1789 msg = "client/server protocol";
1792 msg = "lock busy on server";
1795 msg = "SMTP transaction";
1798 error(0, 0, "undefined");
1801 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
1802 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
1803 || ok==PS_LOCKBUSY || ok==PS_SMTP)
1804 error(0, -1, "%s error while fetching from %s", msg, ctl->server.names->id);
1807 signal(SIGALRM, sigsave);
1811 #if defined(HAVE_STDARG_H)
1812 void gen_send(int sock, char *fmt, ... )
1813 /* assemble command in printf(3) style and send to the server */
1815 void gen_send(sock, fmt, va_alist)
1816 /* assemble command in printf(3) style and send to the server */
1817 int sock; /* socket to which server is connected */
1818 const char *fmt; /* printf-style format */
1822 char buf [POPBUFSIZE+1];
1825 if (protocol->tagged)
1826 (void) sprintf(buf, "%s ", GENSYM);
1830 #if defined(HAVE_STDARG_H)
1835 #ifdef HAVE_VSNPRINTF
1836 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
1838 vsprintf(buf + strlen(buf), fmt, ap);
1842 strcat(buf, "\r\n");
1843 SockWrite(sock, buf, strlen(buf));
1845 if (outlevel == O_VERBOSE)
1849 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
1853 sp = cp + strlen(shroud);
1859 buf[strlen(buf)-2] = '\0';
1860 error(0, 0, "%s> %s", protocol->name, buf);
1864 int gen_recv(sock, buf, size)
1865 /* get one line of input from the server */
1866 int sock; /* socket to which server is connected */
1867 char *buf; /* buffer to receive input */
1868 int size; /* length of buffer */
1870 if (SockRead(sock, buf, size) == -1)
1874 if (buf[strlen(buf)-1] == '\n')
1875 buf[strlen(buf)-1] = '\0';
1876 if (buf[strlen(buf)-1] == '\r')
1877 buf[strlen(buf)-1] = '\r';
1878 if (outlevel == O_VERBOSE)
1879 error(0, 0, "%s< %s", protocol->name, buf);
1884 #if defined(HAVE_STDARG_H)
1885 int gen_transact(int sock, char *fmt, ... )
1886 /* assemble command in printf(3) style, send to server, accept a response */
1888 int gen_transact(int sock, fmt, va_alist)
1889 /* assemble command in printf(3) style, send to server, accept a response */
1890 int sock; /* socket to which server is connected */
1891 const char *fmt; /* printf-style format */
1896 char buf [POPBUFSIZE+1];
1899 if (protocol->tagged)
1900 (void) sprintf(buf, "%s ", GENSYM);
1904 #if defined(HAVE_STDARG_H)
1909 #ifdef HAVE_VSNPRINTF
1910 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
1912 vsprintf(buf + strlen(buf), fmt, ap);
1916 strcat(buf, "\r\n");
1917 SockWrite(sock, buf, strlen(buf));
1919 if (outlevel == O_VERBOSE)
1923 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
1927 sp = cp + strlen(shroud);
1933 buf[strlen(buf)-1] = '\0';
1934 error(0, 0, "%s> %s", protocol->name, buf);
1937 /* we presume this does its own response echoing */
1938 ok = (protocol->parse_response)(sock, buf);
1939 set_timeout(mytimeout);
1944 /* driver.c ends here */