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.
16 #endif /* HAVE_MEMORY_H */
17 #if defined(STDC_HEADERS)
20 #if defined(HAVE_UNISTD_H)
23 #if defined(HAVE_STDARG_H)
28 #if defined(HAVE_ALLOCA_H)
35 #if defined(HAVE_SYS_ITIMER_H)
36 #include <sys/itimer.h>
41 #ifndef HAVE_STRFTIME /* For ctime prototype */
42 #include <sys/types.h>
46 #ifdef HAVE_GETHOSTBYNAME
49 #endif /* HAVE_GETHOSTBYNAME */
52 #if defined (__bsdi__)
53 #include <des.h> /* order of includes matters */
55 #define krb_get_err_text(e) (krb_err_txt[e])
57 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
58 #define krb_get_err_text(e) (krb_err_txt[e])
64 #endif /* ! defined (__FreeBSD__) */
65 #endif /* ! defined (__bsdi__) */
66 #include <netinet/in.h>
68 #endif /* KERBEROS_V4 */
72 #endif /* KEREROS_V5 */
74 #include "fetchmail.h"
78 /* BSD portability hack...I know, this is an ugly place to put it */
79 #if !defined(SIGCHLD) && defined(SIGCLD)
80 #define SIGCHLD SIGCLD
84 #define SMTP_PORT "smtp" /* standard SMTP service port */
86 #define SMTP_PORT 25 /* standard SMTP service port */
89 #ifndef strstr /* glibc-2.1 declares this as a macro */
90 extern char *strstr(); /* needed on sysV68 R3V7.1. */
93 int fetchlimit; /* how often to tear down the server connection */
94 int batchcount; /* count of messages sent in current batch */
95 flag peek_capable; /* can we peek for better error recovery? */
96 int pass; /* how many times have we re-polled? */
98 static const struct method *protocol;
99 static jmp_buf restart;
103 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
105 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
106 static int mytimeout; /* value of nonreponse timeout */
107 static int msglen; /* actual message length */
108 static int mimemsg; /* bitmask indicating MIME body-type */
110 /* use these to track what was happening when the nonresponse timer fired */
111 #define GENERAL_WAIT 0 /* unknown wait type */
112 #define SERVER_WAIT 1 /* waiting for mailserver response */
113 #define LISTENER_WAIT 2 /* waiting for listener initialization */
114 #define FORWARDING_WAIT 3 /* waiting for listener response */
117 static void set_timeout(int timeleft)
118 /* reset the nonresponse-timeout */
121 struct itimerval ntimeout;
123 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
124 ntimeout.it_value.tv_sec = timeleft;
125 ntimeout.it_value.tv_usec = 0;
126 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
130 static void timeout_handler (int signal)
131 /* handle server-timeout SIGALRM signal */
136 #define XMIT_ACCEPT 1
137 #define XMIT_REJECT 2
138 #define XMIT_ANTISPAM 3
139 static int accept_count, reject_count;
143 static int is_host_alias(const char *name, struct query *ctl)
144 /* determine whether name is a DNS alias of the hostname */
147 struct mxentry *mxp, *mxrecords;
149 struct hostdata *lead_server =
150 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
153 * The first two checks are optimizations that will catch a good
156 * (1) check against the `true name' deduced from the poll label
157 * and the via option (if present) at the beginning of the poll cycle.
158 * Odds are good this will either be the mailserver's FQDN or a suffix of
159 * it with the mailserver's domain's default host name omitted.
161 * (2) Then check the rest of the `also known as'
162 * cache accumulated by previous DNS checks. This cache is primed
163 * by the aka list option.
165 * Any of these on a mail address is definitive. Only if the
166 * name doesn't match any is it time to call the bind library.
167 * If this happens odds are good we're looking at an MX name.
169 if (strcasecmp(lead_server->truename, name) == 0)
171 else if (str_in_list(&lead_server->akalist, name, TRUE))
173 else if (!ctl->server.dns)
176 #ifndef HAVE_RES_SEARCH
180 * The only code that calls the BIND library is here and in the
181 * start-of-query probe with gethostbyname(3).
183 * We know DNS service was up at the beginning of this poll cycle.
184 * If it's down, our nameserver has crashed. We don't want to try
185 * delivering the current message or anything else from this
186 * mailbox until it's back up.
188 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
190 if (strcasecmp(ctl->server.truename, he->h_name) == 0)
198 case HOST_NOT_FOUND: /* specified host is unknown */
199 case NO_ADDRESS: /* valid, but does not have an IP address */
202 case NO_RECOVERY: /* non-recoverable name server error */
203 case TRY_AGAIN: /* temporary error on authoritative server */
205 if (outlevel != O_SILENT)
206 putchar('\n'); /* terminate the progress message */
208 "nameserver failure while looking for `%s' during poll of %s.",
209 name, ctl->server.pollname);
215 * We're only here if DNS was OK but the gethostbyname() failed
216 * with a HOST_NOT_FOUND or NO_ADDRESS error.
217 * Search for a name match on MX records pointing to the server.
220 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
224 case HOST_NOT_FOUND: /* specified host is unknown */
225 case NO_ADDRESS: /* valid, but does not have an IP address */
229 case NO_RECOVERY: /* non-recoverable name server error */
230 case TRY_AGAIN: /* temporary error on authoritative server */
233 "nameserver failure while looking for `%s' during poll of %s.",
234 name, ctl->server.pollname);
241 for (mxp = mxrecords; mxp->name; mxp++)
242 if (strcasecmp(ctl->server.truename, mxp->name) == 0)
248 /* add this name to relevant server's `also known as' list */
249 save_str(&lead_server->akalist, name, 0);
251 #endif /* HAVE_RES_SEARCH */
254 static void map_name(name, ctl, xmit_names)
255 /* add given name to xmit_names if it matches declared localnames */
256 const char *name; /* name to map */
257 struct query *ctl; /* list of permissible aliases */
258 struct idlist **xmit_names; /* list of recipient names parsed out */
264 lname = idpair_find(&ctl->localnames, name+off);
265 if (!lname && ctl->wildcard)
268 if (lname != (char *)NULL)
270 if (outlevel == O_VERBOSE)
271 error(0, 0, "mapped %s to local %s", name, lname);
272 save_str(xmit_names, lname, XMIT_ACCEPT);
277 void find_server_names(hdr, ctl, xmit_names)
278 /* parse names out of a RFC822 header into an ID list */
279 const char *hdr; /* RFC822 header in question */
280 struct query *ctl; /* list of permissible aliases */
281 struct idlist **xmit_names; /* list of recipient names parsed out */
283 if (hdr == (char *)NULL)
289 for (cp = nxtaddr(hdr);
296 * If the name of the user begins with a qmail virtual
297 * domain prefix, ignore the prefix. Doing this here
298 * means qvirtual will work either with ordinary name
299 * mapping or with a localdomains option.
301 if (ctl->server.qvirtual)
303 int sl = strlen(ctl->server.qvirtual);
305 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
309 if ((atsign = strchr(cp, '@'))) {
313 * Does a trailing segment of the hostname match something
314 * on the localdomains list? If so, save the whole name
317 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
320 rhs = atsign + (strlen(atsign) - strlen(idp->id));
322 (rhs[-1] == '.' || rhs[-1] == '@') &&
323 strcasecmp(rhs, idp->id) == 0)
325 if (outlevel == O_VERBOSE)
326 error(0, 0, "passed through %s matching %s",
328 save_str(xmit_names, cp, XMIT_ACCEPT);
334 /* if we matched a local domain, idp != NULL */
338 * Check to see if the right-hand part is an alias
339 * or MX equivalent of the mailserver. If it's
340 * not, skip this name. If it is, we'll keep
341 * going and try to find a mapping to a client name.
343 if (!is_host_alias(atsign+1, ctl))
345 save_str(xmit_names, cp, XMIT_REJECT);
351 map_name(cp, ctl, xmit_names);
357 static char *parse_received(struct query *ctl, char *bufp)
358 /* try to extract real address from the Received line */
359 /* If a valid Received: line is found, we return the full address in
360 * a buffer which can be parsed from nxtaddr(). This is to ansure that
361 * the local domain part of the address can be passed along in
362 * find_server_names() if it contains one.
363 * Note: We should return a dummy header containing the address
364 * which makes nxtaddr() behave correctly.
367 char *ok = (char *)NULL;
368 static char rbuf[HOSTLEN + USERNAMELEN + 4];
371 * Try to extract the real envelope addressee. We look here
372 * specifically for the mailserver's Received line.
373 * Note: this will only work for sendmail, or an MTA that
374 * shares sendmail's convention for embedding the envelope
375 * address in the Received line. Sendmail itself only
376 * does this when the mail has a single recipient.
378 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
382 /* extract space-delimited token after "by " */
383 for (sp = ok + 3; isspace(*sp); sp++)
386 for (; !isspace(*sp); sp++)
391 * If it's a DNS name of the mail server, look for the
392 * recipient name after a following "for". Otherwise
395 if (is_host_alias(rbuf, ctl) &&
396 (ok = strstr(sp, "for ")) &&
401 *tp++ = ':'; /* Here is the hack. This is to be friend */
402 *tp++ = ' '; /* with nxtaddr()... */
405 while (*sp == '@') /* skip routes */
406 while (*sp && *sp++ != ':')
408 while (*sp && *sp != '>' && *sp != ';')
413 /* uh oh -- whitespace here can't be right! */
419 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
429 if (outlevel == O_VERBOSE) {
430 char *lf = rbuf + strlen(rbuf)-1;
432 error(0, 0, "found Received address `%s'", rbuf+2);
439 static int smtp_open(struct query *ctl)
440 /* try to open a socket to the appropriate SMTP server for this query */
442 /* maybe it's time to close the socket in order to force delivery */
443 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
445 close(ctl->smtp_socket);
446 ctl->smtp_socket = -1;
450 /* if no socket to any SMTP host is already set up, try to open one */
451 if (ctl->smtp_socket == -1)
454 * RFC 1123 requires that the domain name in HELO address is a
455 * "valid principal domain name" for the client host. If we're
456 * running in invisible mode, violate this with malice
457 * aforethought in order to make the Received headers and
458 * logging look right.
460 * In fact this code relies on the RFC1123 requirement that the
461 * SMTP listener must accept messages even if verification of the
462 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
464 * How we compute the true mailhost name to pass to the
465 * listener doesn't affect behavior on RFC1123- violating
466 * listener that check for name match; we're going to lose
467 * on those anyway because we can never give them a name
468 * that matches the local machine fetchmail is running on.
469 * What it will affect is the listener's logging.
472 char *id_me = use_invisible ? ctl->server.truename : fetchmailhost;
473 int oldphase = phase;
478 * Run down the SMTP hunt list looking for a server that's up.
479 * Use both explicit hunt entries (value TRUE) and implicit
480 * (default) ones (value FALSE).
483 phase = LISTENER_WAIT;
485 set_timeout(ctl->server.timeout);
486 for (idp = ctl->smtphunt; idp; idp = idp->next)
488 char *cp, *parsed_host = alloca(strlen(idp->id) + 1);
490 char *portnum = SMTP_PORT;
492 int portnum = SMTP_PORT;
495 ctl->smtphost = idp->id; /* remember last host tried. */
497 strcpy(parsed_host, idp->id);
498 if ((cp = strrchr(parsed_host, '/')))
508 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
511 /* first, probe for ESMTP */
512 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
513 SMTP_ehlo(ctl->smtp_socket, id_me,
514 &ctl->server.esmtp_options) == SM_OK)
518 * RFC 1869 warns that some listeners hang up on a failed EHLO,
519 * so it's safest not to assume the socket will still be good.
521 close(ctl->smtp_socket);
522 ctl->smtp_socket = -1;
524 /* if opening for ESMTP failed, try SMTP */
525 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
528 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
529 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
532 close(ctl->smtp_socket);
533 ctl->smtp_socket = -1;
539 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
540 error(0, 0, "forwarding to %s", ctl->smtphost);
542 return(ctl->smtp_socket);
545 /* these are shared by stuffline, readheaders and readbody */
547 static RETSIGTYPE (*sigchld)();
548 static int sizeticker;
550 static int stuffline(struct query *ctl, char *buf)
551 /* ship a line to the given control block's output sink (SMTP server or MDA) */
556 /* The line may contain NUL characters. Find the last char to use
557 * -- the real line termination is the sequence "\n\0".
560 while ((last += strlen(last)) && (last[-1] != '\n'))
563 /* fix message lines that have only \n termination (for qmail) */
566 if (last - 1 == buf || last[-2] != '\r')
575 phase = FORWARDING_WAIT;
578 * SMTP byte-stuffing. We only do this if the protocol does *not*
579 * use .<CR><LF> as EOM. If it does, the server will already have
580 * decorated any . lines it sends back up.
583 if (protocol->delimited) /* server has already byte-stuffed */
588 /* writing to SMTP, leave the byte-stuffing in place */;
590 else /* if (!protocol->delimited) -- not byte-stuffed already */
593 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
595 /* leave it alone */;
598 /* we may need to strip carriage returns */
603 for (sp = tp = buf; sp < last; sp++)
612 n = fwrite(buf, 1, last - buf, sinkfp);
613 else if (ctl->smtp_socket != -1)
614 n = SockWrite(ctl->smtp_socket, buf, last - buf);
621 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
623 static int readheaders(sock, fetchlen, reallen, ctl, num)
624 /* read message headers and ship to SMTP or MDA */
625 int sock; /* to which the server is connected */
626 long fetchlen; /* length of message according to fetch response */
627 long reallen; /* length of message according to getsizes */
628 struct query *ctl; /* query control record */
629 int num; /* index of message */
634 struct addrblk *next;
636 struct addrblk *to_addrchain = NULL;
637 struct addrblk **to_chainptr = &to_addrchain;
638 struct addrblk *resent_to_addrchain = NULL;
639 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
641 char buf[MSGBUFSIZE+1];
642 char return_path[HOSTLEN + USERNAMELEN + 4];
643 int from_offs, reply_to_offs, resent_from_offs;
644 int app_from_offs, sender_offs, resent_sender_offs;
646 char *headers, *received_for, *destaddr, *rcv, *cp;
647 int n, linelen, oldlen, ch, remaining, skipcount;
648 struct idlist *idp, *xmit_names;
649 flag good_addresses, bad_addresses, has_nuls;
650 flag no_local_matches = FALSE;
655 has_nuls = headers_ok = FALSE;
656 return_path[0] = '\0';
657 olderrs = ctl->errcount;
659 /* read message headers */
660 headers = received_for = NULL;
661 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
662 sender_offs = resent_sender_offs = env_offs = -1;
668 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
672 line = xmalloc(sizeof(buf));
676 set_timeout(ctl->server.timeout);
677 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
687 /* lines may not be properly CRLF terminated; fix this for qmail */
690 cp = buf + strlen(buf) - 1;
691 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
700 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
704 /* check for end of headers */
708 has_nuls = (linelen != strlen(line));
710 goto process_headers;
714 * Check for end of message immediately. If one of your folders
715 * has been mangled, the delimiter may occur directly after the
718 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
721 has_nuls = (linelen != strlen(line));
722 goto process_headers;
725 /* we may need to grab RFC822 continuations */
726 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
728 /* write the message size dots */
729 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
731 sizeticker += linelen;
732 while (sizeticker >= SIZETICKER)
735 sizeticker -= SIZETICKER;
739 /* we see an ordinary (non-header, non-message-delimiter line */
740 has_nuls = (linelen != strlen(line));
743 * The University of Washington IMAP server (the reference
744 * implementation of IMAP4 written by Mark Crispin) relies
745 * on being able to keep base-UID information in a special
746 * message at the head of the mailbox. This message should
747 * neither be deleted nor forwarded.
751 * We disable this check under POP2 because there's no way to
752 * prevent deletion of the message. So at least we ought to
753 * forward it to the user so he or she will have some clue
754 * that things have gone awry.
756 if (protocol->port != 109)
757 #endif /* POP2_ENABLE */
758 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
765 * This code prevents fetchmail from becoming an accessory after
766 * the fact to upstream sendmails with the `E' option on. This
767 * can result in an escaped Unix From_ line at the beginning of
768 * the headers. If fetchmail just passes it through, the client
769 * listener may think the message has *no* headers (since the first)
770 * line it sees doesn't look RFC822-conformant) and fake up a set.
772 * What the user would see in this case is bogus (synthesized)
773 * headers, followed by a blank line, followed by the >From,
774 * followed by the real headers, followed by a blank line,
777 * We forestall this lossage by tossing anything that looks
778 * like an escaped From_ line in headers. These aren't RFC822
779 * so our conscience is clear...
781 if (!strncasecmp(line, ">From ", 6))
788 * If we see a Status line, it may have been inserted by an MUA
789 * on the mail host, or it may have been inserted by the server
790 * program after the headers in the transaction stream. This
791 * can actually hose some new-mail notifiers such as xbuffy,
792 * which assumes any Status line came from a *local* MDA and
793 * therefore indicates that the message has been seen.
795 * Some buggy POP servers (including at least the 3.3(20)
796 * version of the one distributed with IMAP) insert empty
797 * Status lines in the transaction stream; we'll chuck those
798 * unconditionally. Nonempty ones get chucked if the user
799 * turns on the dropstatus flag.
803 if (!strncasecmp(line, "Status:", 7))
805 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
810 while (*cp && isspace(*cp)) cp++;
811 if (!*cp || ctl->dropstatus)
820 line = reply_hack(line, ctl->server.truename);
823 * OK, this is messy. If we're forwarding by SMTP, it's the
824 * SMTP-receiver's job (according to RFC821, page 22, section
825 * 4.1.1) to generate a Return-Path line on final delivery.
826 * The trouble is, we've already got one because the
827 * mailserver's SMTP thought *it* was responsible for final
830 * Stash away the contents of Return-Path for use in generating
831 * MAIL FROM later on, then prevent the header from being saved
832 * with the others. In effect, we strip it off here.
834 * If the SMTP server conforms to the standards, and fetchmail gets the
835 * envelope sender from the Return-Path, the new Return-Path should be
836 * exactly the same as the original one.
838 * We do *not* want to ignore empty Return-Path headers. These should
839 * be passed through as a way of indicating that a message should
840 * not trigger bounces if delivery fails. What we *do* need to do is
841 * make sure we never try to rewrite such a blank Return-Path. We
842 * handle this with a check for <> in the rewrite logic.
844 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
846 strcpy(return_path, cp);
855 oldlen = strlen(line);
856 headers = xmalloc(oldlen + 1);
857 (void) strcpy(headers, line);
865 newlen = oldlen + strlen(line);
866 headers = (char *) realloc(headers, newlen + 1);
867 if (headers == NULL) {
871 strcpy(headers + oldlen, line);
873 line = headers + oldlen;
877 if (!strncasecmp("From:", line, 5))
878 from_offs = (line - headers);
879 else if (!strncasecmp("Reply-To:", line, 9))
880 reply_to_offs = (line - headers);
881 else if (!strncasecmp("Resent-From:", line, 12))
882 resent_from_offs = (line - headers);
883 else if (!strncasecmp("Apparently-From:", line, 16))
884 app_from_offs = (line - headers);
885 else if (!strncasecmp("Sender:", line, 7))
886 sender_offs = (line - headers);
887 else if (!strncasecmp("Resent_Sender:", line, 14))
888 resent_sender_offs = (line - headers);
890 else if (!strncasecmp("Message-Id:", buf, 11))
892 if (ctl->server.uidl)
896 buf[IDLEN+12] = 0; /* prevent stack overflow */
897 sscanf(buf+12, "%s", id);
898 if (!str_find( &ctl->newsaved, num))
900 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
901 new->val.status.num = num;
906 else if (!MULTIDROP(ctl))
909 else if (!strncasecmp("To:", line, 3)
910 || !strncasecmp("Cc:", line, 3)
911 || !strncasecmp("Bcc:", line, 4)
912 || !strncasecmp("Apparently-To:", line, 14))
914 *to_chainptr = xmalloc(sizeof(struct addrblk));
915 (*to_chainptr)->offset = (line - headers);
916 to_chainptr = &(*to_chainptr)->next;
920 else if (!strncasecmp("Resent-To:", line, 10)
921 || !strncasecmp("Resent-Cc:", line, 10)
922 || !strncasecmp("Resent-Bcc:", line, 11))
924 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
925 (*resent_to_chainptr)->offset = (line - headers);
926 resent_to_chainptr = &(*resent_to_chainptr)->next;
927 *resent_to_chainptr = NULL;
930 else if (ctl->server.envelope != STRING_DISABLED)
932 if (ctl->server.envelope
933 && strcasecmp(ctl->server.envelope, "Received"))
935 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
937 strlen(ctl->server.envelope)))
939 if (skipcount++ != ctl->server.envskip)
941 env_offs = (line - headers);
944 else if (!received_for && !strncasecmp("Received:", line, 9))
946 if (skipcount++ != ctl->server.envskip)
948 received_for = parse_received(ctl, line);
955 * We want to detect this early in case there are so few headers that the
956 * dispatch logic barfs.
960 if (outlevel > O_SILENT)
961 error(0,0,"message delimiter found while scanning headers");
965 * Hack time. If the first line of the message was blank, with no headers
966 * (this happens occasionally due to bad gatewaying software) cons up
967 * a set of fake headers.
969 * If you modify the fake header template below, be sure you don't
970 * make either From or To address @-less, otherwise the reply_hack
971 * logic will do bad things.
973 if (headers == (char *)NULL)
976 snprintf(buf, sizeof(buf),
979 #endif /* HAVE_SNPRINTF */
980 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
981 fetchmailhost, user, ctl->remotename, ctl->server.truename);
982 headers = xstrdup(buf);
986 * We can now process message headers before reading the text.
987 * In fact we have to, as this will tell us where to forward to.
990 /* Decode MIME encoded headers. We MUST do this before
991 * looking at the Content-Type / Content-Transfer-Encoding
992 * headers (RFC 2046).
994 if (ctl->mimedecode) {
995 UnMimeHeader(headers);
997 /* Check for MIME headers indicating possible 8-bit data */
998 mimemsg = MimeBodyType(headers);
1001 * If there is a Return-Path address on the message, this was
1002 * almost certainly the MAIL FROM address given the originating
1003 * sendmail. This is the best thing to use for logging the
1004 * message origin (it sets up the right behavior for bounces and
1005 * mailing lists). Otherwise, fall down to the next available
1006 * envelope address wich is the most probable real sender
1007 * respectively. *** The order is important! ***
1008 * This is especially useful when receiving mailing list
1009 * messages in multidrop mode. if a local address doesn't
1010 * exist, the bounce message won't be returned blindly to the
1011 * author or to the list itself but rather to the list manager
1012 * (ex: specified by "Sender:") wich is less anoying. This is
1013 * true for most mailing list packages.
1015 if( !return_path[0] ){
1017 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
1018 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
1019 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
1020 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
1021 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
1022 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
1023 if (ap) strcpy( return_path, ap );
1026 /* cons up a list of local recipients */
1027 xmit_names = (struct idlist *)NULL;
1028 bad_addresses = good_addresses = accept_count = reject_count = 0;
1029 /* is this a multidrop box? */
1032 if (env_offs > -1) /* We have the actual envelope addressee */
1033 find_server_names(headers + env_offs, ctl, &xmit_names);
1034 else if (received_for)
1036 * We have the Received for addressee.
1037 * It has to be a mailserver address, or we
1038 * wouldn't have got here.
1039 * We use find_server_names() to let local
1040 * hostnames go through.
1042 find_server_names(received_for, ctl, &xmit_names);
1045 * We haven't extracted the envelope address.
1046 * So check all the "Resent-To" header addresses if
1047 * they exist. If and only if they don't, consider
1048 * the "To" adresses.
1050 register struct addrblk *nextptr;
1051 if (resent_to_addrchain) {
1052 /* delete the "To" chain and substitute it
1053 * with the "Resent-To" list
1055 while (to_addrchain) {
1056 nextptr = to_addrchain->next;
1058 to_addrchain = nextptr;
1060 to_addrchain = resent_to_addrchain;
1061 resent_to_addrchain = NULL;
1063 /* now look for remaining adresses */
1064 while (to_addrchain) {
1065 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
1066 nextptr = to_addrchain->next;
1068 to_addrchain = nextptr;
1073 no_local_matches = TRUE;
1074 save_str(&xmit_names, user, XMIT_ACCEPT);
1075 if (outlevel == O_VERBOSE)
1077 "no local matches, forwarding to %s",
1081 else /* it's a single-drop box, use first localname */
1082 save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
1086 * Time to either address the message or decide we can't deliver it yet.
1088 if (ctl->errcount > olderrs) /* there were DNS errors above */
1090 if (outlevel == O_VERBOSE)
1091 error(0,0, "forwarding and deletion suppressed due to DNS errors");
1093 free_str_list(&xmit_names);
1094 return(PS_TRANSIENT);
1096 else if (ctl->mda) /* we have a declared MDA */
1099 char *names, *before, *after;
1101 for (idp = xmit_names; idp; idp = idp->next)
1102 if (idp->val.status.mark == XMIT_ACCEPT)
1105 destaddr = "localhost";
1107 length = strlen(ctl->mda) + 1;
1108 before = xstrdup(ctl->mda);
1110 /* sub user addresses for %T (or %s for backward compatibility) */
1112 if (strstr(before, "%s") || (cp = strstr(before, "%T")))
1116 if (cp && cp[1] == 'T')
1119 /* \177 had better be out-of-band for MDA commands */
1120 for (sp = before; *sp; sp++)
1121 if (*sp == '%' && sp[1] != 's' && sp[1] != 'T')
1125 * We go through this in order to be able to handle very
1126 * long lists of users and (re)implement %s.
1128 for (idp = xmit_names; idp; idp = idp->next)
1129 if (idp->val.status.mark == XMIT_ACCEPT)
1130 length += (strlen(idp->id) + 1);
1132 names = (char *)xmalloc(++length);
1134 for (idp = xmit_names; idp; idp = idp->next)
1135 if (idp->val.status.mark == XMIT_ACCEPT)
1137 strcat(names, idp->id);
1140 after = (char *)xmalloc(length);
1142 snprintf(after, length, before, names);
1144 sprintf(after, before, names);
1145 #endif /* SNPRINTF */
1150 for (sp = before; *sp; sp++)
1155 /* substitute From address for %F */
1156 if ((cp = strstr(before, "%F")))
1158 char *from = return_path;
1161 /* \177 had better be out-of-band for MDA commands */
1162 for (sp = before; *sp; sp++)
1163 if (*sp == '%' && sp[1] != 'F')
1166 length += strlen(from);
1167 after = (char *)xmalloc(length);
1170 snprintf(after, length, before, from);
1172 sprintf(after, before, from);
1173 #endif /* SNPRINTF */
1177 for (sp = before; *sp; sp++)
1182 if (outlevel == O_VERBOSE)
1183 error(0, 0, "about to deliver with: %s", before);
1187 * Arrange to run with user's permissions if we're root.
1188 * This will initialize the ownership of any files the
1189 * MDA creates properly. (The seteuid call is available
1190 * under all BSDs and Linux)
1193 #endif /* HAVE_SETEUID */
1195 sinkfp = popen(before, "w");
1199 /* this will fail quietly if we didn't start as root */
1201 #endif /* HAVE_SETEUID */
1205 error(0, 0, "MDA open failed");
1207 free_str_list(&xmit_names);
1211 sigchld = signal(SIGCHLD, SIG_DFL);
1215 char *ap, options[MSGBUFSIZE], addr[128];
1217 /* build a connection to the SMTP listener */
1218 if ((smtp_open(ctl) == -1))
1220 error(0, errno, "SMTP connect to %s failed",
1221 ctl->smtphost ? ctl->smtphost : "localhost");
1223 free_str_list(&xmit_names);
1228 * Compute ESMTP options.
1231 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
1232 if (ctl->pass8bits || (mimemsg & MSG_IS_8BIT))
1233 strcpy(options, " BODY=8BITMIME");
1234 else if (mimemsg & MSG_IS_7BIT)
1235 strcpy(options, " BODY=7BIT");
1238 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1239 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1242 * Try to get the SMTP listener to take the Return-Path
1243 * address as MAIL FROM . If it won't, fall back on the
1244 * calling-user ID. This won't affect replies, which use the
1245 * header From address anyway.
1247 * RFC 1123 requires that the domain name part of the
1248 * MAIL FROM address be "canonicalized", that is a
1249 * FQDN or MX but not a CNAME. We'll assume the From
1250 * header is already in this form here (it certainly
1251 * is if rewrite is on). RFC 1123 is silent on whether
1252 * a nonexistent hostname part is considered canonical.
1254 * This is a potential problem if the MTAs further upstream
1255 * didn't pass canonicalized From/Return-Path lines, *and* the
1256 * local SMTP listener insists on them.
1258 ap = (return_path[0]) ? return_path : user;
1259 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1261 int smtperr = atoi(smtp_response);
1263 if (smtperr == ctl->antispam)
1266 * SMTP listener explicitly refuses to deliver mail
1267 * coming from this address, probably due to an
1268 * anti-spam domain exclusion. Respect this. Don't
1269 * try to ship the message, and don't prevent it from
1270 * being deleted. Typical values:
1272 * 571 = sendmail's "unsolicited email refused"
1273 * 501 = exim's old antispam response
1274 * 550 = exim's new antispam response (temporary)
1276 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1278 free_str_list(&xmit_names);
1283 * Suppress error message only if the response specifically
1284 * meant `excluded for policy reasons'. We *should* see
1285 * an error when the return code is less specific.
1288 error(0, -1, "SMTP error: %s", smtp_response);
1292 case 452: /* insufficient system storage */
1294 * Temporary out-of-queue-space condition on the
1295 * ESMTP server. Don't try to ship the message,
1296 * and suppress deletion so it can be retried on
1297 * a future retrieval cycle.
1299 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1301 free_str_list(&xmit_names);
1302 return(PS_TRANSIENT);
1304 case 552: /* message exceeds fixed maximum message size */
1305 case 553: /* invalid sending domain */
1307 * Permanent no-go condition on the
1308 * ESMTP server. Don't try to ship the message,
1309 * and allow it to be deleted.
1311 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1313 free_str_list(&xmit_names);
1316 default: /* retry with invoking user's address */
1317 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1319 error(0, -1, "SMTP error: %s", smtp_response);
1321 free_str_list(&xmit_names);
1322 return(PS_SMTP); /* should never happen */
1328 * Now list the recipient addressees
1330 * RFC 1123 requires that the domain name part of the
1331 * RCPT TO address be "canonicalized", that is a FQDN
1332 * or MX but not a CNAME. Some listeners (like exim)
1335 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1337 for (idp = xmit_names; idp; idp = idp->next)
1338 if (idp->val.status.mark == XMIT_ACCEPT)
1340 if (strchr(idp->id, '@'))
1341 strcpy(addr, idp->id);
1343 #ifdef HAVE_SNPRINTF
1344 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1346 sprintf(addr, "%s@%s", idp->id, destaddr);
1347 #endif /* HAVE_SNPRINTF */
1349 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1354 idp->val.status.mark = XMIT_ANTISPAM;
1356 "SMTP listener doesn't like recipient address `%s'",
1360 if (!good_addresses)
1362 #ifdef HAVE_SNPRINTF
1363 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1365 sprintf(addr, "%s@%s", user, destaddr);
1366 #endif /* HAVE_SNPRINTF */
1368 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1370 error(0, 0, "can't even send to calling user!");
1372 free_str_list(&xmit_names);
1377 /* tell it we're ready to send data */
1378 SMTP_data(ctl->smtp_socket);
1383 * Some server/sendmail combinations cause problems when our
1384 * synthetic Received line is before the From header. Cope
1387 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1392 n = stuffline(ctl, headers);
1395 if (!use_invisible && n != -1)
1397 /* utter any per-message Received information we need here */
1398 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1399 n = stuffline(ctl, buf);
1403 * We used to include ctl->remotename in this log line,
1404 * but this can be secure information that would be bad
1407 sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1411 n = stuffline(ctl, buf);
1417 if (good_addresses == 0)
1420 "for <%s@%s> (by default); ",
1423 else if (good_addresses == 1)
1425 for (idp = xmit_names; idp; idp = idp->next)
1426 if (idp->val.status.mark == XMIT_ACCEPT)
1427 break; /* only report first address */
1428 if (strchr(idp->id, '@'))
1429 sprintf(buf+1, "for <%s>", idp->id);
1431 sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1432 sprintf(buf+strlen(buf), " (%s); ",
1433 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1439 #ifdef HAVE_STRFTIME
1441 * Conform to RFC822. This is typically going to emit
1442 * a three-letter timezone for %Z, which is going to
1443 * be marked "obsolete syntax" in 822bis. Note that we
1444 * generate a 4-digit year here.
1446 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1447 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1450 * This is really just a portability fallback, as the
1451 * date format ctime(3) emits is not RFC822
1454 strcat(buf, ctime(&now));
1455 #endif /* HAVE_STRFTIME */
1456 n = stuffline(ctl, buf);
1462 n = stuffline(ctl, rcv); /* ship out rest of headers */
1466 error(0, errno, "writing RFC822 headers");
1471 signal(SIGCHLD, sigchld);
1474 free_str_list(&xmit_names);
1477 else if (outlevel == O_VERBOSE)
1480 /* write error notifications */
1481 if (no_local_matches || has_nuls || bad_addresses)
1484 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1487 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1488 if (no_local_matches)
1490 if (reject_count != 1)
1491 strcat(errhd, "no recipient addresses matched declared local names");
1494 for (idp = xmit_names; idp; idp = idp->next)
1495 if (idp->val.status.mark == XMIT_REJECT)
1497 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1503 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1504 strcat(errhd, "; ");
1505 strcat(errhd, "message has embedded NULs");
1510 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1511 strcat(errhd, "; ");
1512 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1513 errlen = strlen(errhd);
1514 for (idp = xmit_names; idp; idp = idp->next)
1515 if (idp->val.status.mark == XMIT_ANTISPAM)
1516 errlen += strlen(idp->id) + 2;
1518 errmsg = alloca(errlen+3);
1519 (void) strcpy(errmsg, errhd);
1520 for (idp = xmit_names; idp; idp = idp->next)
1521 if (idp->val.status.mark == XMIT_ANTISPAM)
1523 strcat(errmsg, idp->id);
1525 strcat(errmsg, ", ");
1530 strcat(errmsg, "\n");
1532 /* ship out the error line */
1534 stuffline(ctl, errmsg);
1537 /* issue the delimiter line */
1542 stuffline(ctl, buf);
1545 free_str_list(&xmit_names);
1546 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1549 static int readbody(sock, ctl, forward, len)
1550 /* read and dispose of a message body presented on sock */
1551 struct query *ctl; /* query control record */
1552 int sock; /* to which the server is connected */
1553 int len; /* length of message */
1554 flag forward; /* TRUE to forward */
1557 unsigned char buf[MSGBUFSIZE+1];
1558 unsigned char *inbufp = buf;
1559 flag issoftline = FALSE;
1561 /* pass through the text lines */
1562 while (protocol->delimited || len > 0)
1564 set_timeout(ctl->server.timeout);
1565 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-1-(inbufp-buf)))==-1)
1572 signal(SIGCHLD, sigchld);
1578 /* write the message size dots */
1581 sizeticker += linelen;
1582 while (sizeticker >= SIZETICKER)
1584 if (outlevel > O_SILENT)
1586 sizeticker -= SIZETICKER;
1591 /* check for end of message */
1592 if (protocol->delimited && *inbufp == '.')
1593 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1595 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1598 msglen--; /* subtract the size of the dot escape */
1602 if (ctl->mimedecode && (mimemsg & MSG_NEEDS_DECODE)) {
1603 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1604 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200)) {
1605 /* Soft linebreak, but less than 200 bytes left in
1606 * input buffer. Rather than doing a buffer overrun,
1607 * ignore the soft linebreak, NL-terminate data and
1608 * deliver what we have now.
1609 * (Who writes lines longer than 2K anyway?)
1611 *inbufp = '\n'; *(inbufp+1) = '\0';
1616 /* ship out the text line */
1617 if (forward && (!issoftline))
1619 int n = stuffline(ctl, buf);
1624 error(0, errno, "writing message text");
1629 signal(SIGCHLD, sigchld);
1633 else if (outlevel == O_VERBOSE)
1643 kerberos_auth (socket, canonical)
1644 /* authenticate to the server host using Kerberos V4 */
1645 int socket; /* socket to server host */
1647 char *canonical; /* server name */
1649 const char *canonical; /* server name */
1652 char * host_primary;
1656 Key_schedule schedule;
1659 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1660 rem = (krb_sendauth (0L, socket, ticket, "pop",
1662 ((char *) (krb_realmofhost (canonical))),
1663 ((unsigned long) 0),
1667 ((struct sockaddr_in *) 0),
1668 ((struct sockaddr_in *) 0),
1671 if (rem != KSUCCESS)
1673 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1674 return (PS_AUTHFAIL);
1678 #endif /* KERBEROS_V4 */
1682 kerberos5_auth(socket, canonical)
1683 /* authernticate to the server host using Kerberos V5 */
1684 int socket; /* socket to server host */
1685 const char *canonical; /* server name */
1687 krb5_error_code retval;
1688 krb5_context context;
1690 krb5_principal client = NULL, server = NULL;
1691 krb5_error *err_ret = NULL;
1693 krb5_auth_context auth_context = NULL;
1695 krb5_init_context(&context);
1696 krb5_init_ets(context);
1697 krb5_auth_con_init(context, &auth_context);
1699 if (retval = krb5_cc_default(context, &ccdef)) {
1700 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1704 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1705 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1709 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1712 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1716 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1717 "KPOPV1.0", client, server,
1718 AP_OPTS_MUTUAL_REQUIRED,
1719 NULL, /* no data to checksum */
1720 0, /* no creds, use ccache instead */
1724 NULL); /* don't need reply */
1726 krb5_free_principal(context, server);
1727 krb5_free_principal(context, client);
1728 krb5_auth_con_free(context, auth_context);
1731 if (err_ret && err_ret->text.length) {
1732 error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1733 error_message(retval),
1734 err_ret->text.length,
1735 err_ret->text.data);
1736 krb5_free_error(context, err_ret);
1738 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1744 #endif /* KERBEROS_V5 */
1746 int do_protocol(ctl, proto)
1747 /* retrieve messages from server using given protocol method table */
1748 struct query *ctl; /* parsed options with merged-in defaults */
1749 const struct method *proto; /* protocol method table */
1751 int ok, js, sock = -1;
1756 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1758 error(0, -1, "Kerberos V4 support not linked.");
1761 #endif /* KERBEROS_V4 */
1764 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1766 error(0, -1, "Kerberos V5 support not linked.");
1769 #endif /* KERBEROS_V5 */
1771 /* lacking methods, there are some options that may fail */
1774 /* check for unsupported options */
1777 "Option --flush is not supported with %s",
1781 else if (ctl->fetchall) {
1783 "Option --all is not supported with %s",
1788 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1791 "Option --limit is not supported with %s",
1799 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1802 /* set up the server-nonresponse timeout */
1803 sigsave = signal(SIGALRM, timeout_handler);
1804 mytimeout = ctl->server.timeout;
1806 if ((js = setjmp(restart)) == 1)
1808 if (phase == SERVER_WAIT)
1810 "timeout after %d seconds waiting for server %s.",
1811 ctl->server.timeout, ctl->server.pollname);
1812 else if (phase == FORWARDING_WAIT)
1814 "timeout after %d seconds waiting for %s.",
1815 ctl->server.timeout,
1816 ctl->mda ? "MDA" : "SMTP");
1817 else if (phase == LISTENER_WAIT)
1819 "timeout after %d seconds waiting for listener to respond.");
1821 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1823 if (ctl->smtp_socket != -1)
1824 close(ctl->smtp_socket);
1833 char buf [POPBUFSIZE+1], *realhost;
1834 int *msgsizes, len, num, count, new, bytes, deletions = 0;
1836 int fetches, dispatches;
1838 int port, fetches, dispatches;
1842 /* execute pre-initialization command, if any */
1843 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1845 sprintf(buf, "pre-connection command failed with status %d", ok);
1851 /* open a socket to the mail server */
1853 port = ctl->server.port ? ctl->server.port : protocol->port;
1855 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1857 if ((sock = SockOpen(realhost,
1858 ctl->server.service ? ctl->server.service : protocol->service,
1859 ctl->server.netsec)) == -1)
1861 if ((sock = SockOpen(realhost, port, NULL)) == -1)
1865 #ifndef EHOSTUNREACH
1866 #define EHOSTUNREACH (-1)
1868 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1870 error_build("fetchmail: %s connection to %s failed: ",
1871 protocol->name, ctl->server.pollname);
1872 #ifdef HAVE_RES_SEARCH
1873 if (h_errno == HOST_NOT_FOUND)
1874 error_complete(0, 0, "host is unknown");
1875 else if (h_errno == NO_ADDRESS)
1876 error_complete(0, 0, "name is valid but has no IP address");
1877 else if (h_errno == NO_RECOVERY)
1878 error_complete(0, 0, "unrecoverable name server error");
1879 else if (h_errno == TRY_AGAIN)
1880 error_complete(0, 0, "temporary name server error");
1882 error_complete(0, 0, "unknown DNS error %d", h_errno);
1884 #endif /* HAVE_RES_SEARCH */
1885 error_complete(0, errno, "local error");
1893 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1895 set_timeout(ctl->server.timeout);
1896 ok = kerberos_auth(sock, ctl->server.truename);
1901 #endif /* KERBEROS_V4 */
1904 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1906 set_timeout(ctl->server.timeout);
1907 ok = kerberos5_auth(sock, ctl->server.truename);
1912 #endif /* KERBEROS_V5 */
1914 /* accept greeting message from mail server */
1915 ok = (protocol->parse_response)(sock, buf);
1919 /* try to get authorized to fetch mail */
1920 if (protocol->getauth)
1922 if (protocol->password_canonify)
1923 (protocol->password_canonify)(shroud, ctl->password);
1925 strcpy(shroud, ctl->password);
1927 ok = (protocol->getauth)(sock, ctl, buf);
1930 if (ok == PS_LOCKBUSY)
1931 error(0, -1, "Lock-busy error on %s@%s",
1933 ctl->server.truename);
1938 error(0, -1, "Authorization failure on %s@%s",
1940 ctl->server.truename);
1946 ctl->errcount = fetches = 0;
1948 /* now iterate over each folder selected */
1949 for (idp = ctl->mailboxes; idp; idp = idp->next)
1956 if (outlevel >= O_VERBOSE)
1958 error(0, 0, "selecting or re-polling folder %s", idp->id);
1960 error(0, 0, "selecting or re-polling default folder");
1962 /* compute # of messages and number of new messages waiting */
1963 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1968 * We need the size of each message before it's
1969 * loaded in order to pass via the ESMTP SIZE
1970 * option. If the protocol has a getsizes method,
1971 * we presume this means it doesn't get reliable
1972 * sizes from message fetch responses.
1974 if (count > 0 && proto->getsizes)
1978 msgsizes = (int *)alloca(sizeof(int) * count);
1979 for (i = 0; i < count; i++)
1982 ok = (proto->getsizes)(sock, count, msgsizes);
1989 for (i = 0; i < count; i++)
1990 bytes += msgsizes[i];
1994 /* show user how many messages we downloaded */
1996 (void) sprintf(buf, "%s at %s (folder %s)",
1997 ctl->remotename, ctl->server.truename, idp->id);
1999 (void) sprintf(buf, "%s at %s",
2000 ctl->remotename, ctl->server.truename);
2001 if (outlevel > O_SILENT)
2002 if (count == -1) /* only used for ETRN */
2003 error(0, 0, "Polling %s", ctl->server.truename);
2004 else if (count != 0)
2006 if (new != -1 && (count - new) > 0)
2007 error_build("%d message%s (%d seen) for %s",
2008 count, count > 1 ? "s" : "", count-new, buf);
2010 error_build("%d message%s for %s",
2011 count, count > 1 ? "s" : "", buf);
2013 error_complete(0, 0, ".");
2015 error_complete(0, 0, " (%d bytes).", bytes);
2019 /* these are pointless in normal daemon mode */
2020 if (pass == 1 && (poll_interval == 0 || outlevel == O_VERBOSE))
2021 error(0, 0, "No mail for %s", buf);
2024 /* very important, this is where we leave the do loop */
2030 if (new == -1 || ctl->fetchall)
2032 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
2037 flag force_retrieval;
2040 * What forces this code is that in POP2 and
2041 * IMAP2bis you can't fetch a message without
2042 * having it marked `seen'. In POP3 and IMAP4, on the
2043 * other hand, you can (peek_capable is set by
2044 * each driver module to convey this; it's not a
2045 * method constant because of the difference between
2046 * IMAP2bis and IMAP4).
2048 * The result of being unable to peek is that if there's
2049 * any kind of transient error (DNS lookup failure, or
2050 * sendmail refusing delivery due to process-table limits)
2051 * the message will be marked "seen" on the server without
2052 * having been delivered. This is not a big problem if
2053 * fetchmail is running in foreground, because the user
2054 * will see a "skipped" message when it next runs and get
2057 * But in daemon mode this leads to the message
2058 * being silently ignored forever. This is not
2061 * We compensate for this by checking the error
2062 * count from the previous pass and forcing all
2063 * messages to be considered new if it's nonzero.
2065 force_retrieval = !peek_capable && (ctl->errcount > 0);
2067 /* read, forward, and delete messages */
2068 for (num = 1; num <= count; num++)
2070 flag toolarge = NUM_NONZERO(ctl->limit)
2071 && msgsizes && (msgsizes[num-1] > ctl->limit);
2072 flag fetch_it = !toolarge
2073 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
2074 flag suppress_delete = FALSE;
2075 flag suppress_forward = FALSE;
2076 flag suppress_readbody = FALSE;
2077 flag retained = FALSE;
2080 * This check copes with Post Office/NT's
2081 * annoying habit of randomly prepending bogus
2082 * LIST items of length -1. Patrick Audley
2083 * <paudley@pobox.com> tells us: LIST shows a
2084 * size of -1, RETR and TOP return "-ERR
2085 * System error - couldn't open message", and
2086 * DELE succeeds but doesn't actually delete
2089 if (msgsizes && msgsizes[num-1] == -1)
2091 if (outlevel >= O_VERBOSE)
2093 "Skipping message %d, length -1",
2098 /* we may want to reject this message if it's old */
2101 if (outlevel > O_SILENT)
2103 error_build("skipping message %d", num);
2105 error_build(" (oversized, %d bytes)",
2111 flag wholesize = !protocol->fetch_body;
2113 /* request a message */
2114 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
2118 /* -1 means we didn't see a size in the response */
2119 if (len == -1 && msgsizes)
2121 len = msgsizes[num - 1];
2125 if (outlevel > O_SILENT)
2127 error_build("reading message %d of %d",
2131 error_build(" (%d %sbytes)",
2132 len, wholesize ? "" : "header ");
2133 if (outlevel == O_VERBOSE)
2134 error_complete(0, 0, "");
2139 /* later we'll test for this before closing */
2140 sinkfp = (FILE *)NULL;
2143 * Read the message headers and ship them to the
2146 ok = readheaders(sock, len, msgsizes[num-1],
2148 if (ok == PS_RETAINED)
2149 suppress_forward = retained = TRUE;
2150 else if (ok == PS_TRANSIENT)
2151 suppress_delete = suppress_forward = TRUE;
2152 else if (ok == PS_REFUSED)
2153 suppress_forward = TRUE;
2154 else if (ok == PS_TRUNCATED)
2155 suppress_readbody = TRUE;
2160 * If we're using IMAP4 or something else that
2161 * can fetch headers separately from bodies,
2162 * it's time to request the body now. This
2163 * fetch may be skipped if we got an anti-spam
2164 * or other PS_REFUSED error response during
2167 if (protocol->fetch_body && !suppress_readbody)
2169 if (outlevel == O_VERBOSE)
2170 fputc('\n', stderr);
2172 if ((ok = (protocol->trail)(sock, ctl, num)))
2175 if (!suppress_forward)
2177 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
2179 if (outlevel > O_SILENT && !wholesize)
2180 error_build(" (%d body bytes) ", len);
2184 /* process the body now */
2187 if (suppress_readbody)
2189 /* When readheaders returns PS_TRUNCATED,
2190 the body (which has no content
2191 has already been read by readheaders,
2192 so we say readbody returned PS_SUCCESS */
2202 if (ok == PS_TRANSIENT)
2203 suppress_delete = suppress_forward = TRUE;
2207 /* tell server we got it OK and resynchronize */
2208 if (protocol->trail)
2210 if (outlevel == O_VERBOSE)
2211 fputc('\n', stderr);
2213 ok = (protocol->trail)(sock, ctl, num);
2219 /* count # messages forwarded on this pass */
2220 if (!suppress_forward)
2224 * Check to see if the numbers matched?
2226 * Yes, some servers foo this up horribly.
2227 * All IMAP servers seem to get it right, and
2228 * so does Eudora QPOP at least in 2.xx
2231 * Microsoft Exchange gets it completely
2232 * wrong, reporting compressed rather than
2233 * actual sizes (so the actual length of
2234 * message is longer than the reported size).
2235 * Another fine example of Microsoft brain death!
2237 * Some older POP servers, like the old UCB
2238 * POP server and the pre-QPOP QUALCOMM
2239 * versions, report a longer size in the LIST
2240 * response than actually gets shipped up.
2241 * It's unclear what is going on here, as the
2242 * QUALCOMM server (at least) seems to be
2243 * reporting the on-disk size correctly.
2245 if (msgsizes && msglen != msgsizes[num-1])
2247 if (outlevel >= O_VERBOSE)
2249 "message %d was not the expected length (%d != %d)",
2250 num, msglen, msgsizes[num-1]);
2253 /* end-of-message processing starts here */
2259 /* close the delivery pipe, we'll reopen before next message */
2261 rc = pclose(sinkfp);
2264 signal(SIGCHLD, sigchld);
2267 error(0, -1, "MDA exited abnormally or returned nonzero status");
2271 else if (!suppress_forward)
2273 /* write message terminator */
2274 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2276 error(0, -1, "SMTP listener refused delivery");
2278 suppress_delete = TRUE;
2286 * At this point in flow of control, either
2287 * we've bombed on a protocol error or had
2288 * delivery refused by the SMTP server
2289 * (unlikely -- I've never seen it) or we've
2290 * seen `accepted for delivery' and the
2291 * message is shipped. It's safe to mark the
2292 * message seen and delete it on the server
2296 /* tell the UID code we've seen this */
2301 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2302 if (sdp->val.status.num == num)
2303 sdp->val.status.mark = UID_SEEN;
2306 /* maybe we delete this message now? */
2309 if (outlevel > O_SILENT)
2310 error_complete(0, 0, " retained");
2312 else if (protocol->delete
2314 && (fetch_it ? !ctl->keep : ctl->flush))
2317 if (outlevel > O_SILENT)
2318 error_complete(0, 0, " flushed");
2319 ok = (protocol->delete)(sock, ctl, num);
2323 delete_str(&ctl->newsaved, num);
2324 #endif /* POP3_ENABLE */
2326 else if (outlevel > O_SILENT)
2327 error_complete(0, 0, " not flushed");
2329 /* perhaps this as many as we're ready to handle */
2330 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2336 * Only re-poll if we had some actual forwards, allowed
2337 * deletions and had no errors.
2338 * Otherwise it is far too easy to get into infinite loops.
2340 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2344 ok = (protocol->logout_cmd)(sock, ctl);
2346 * Hmmmm...arguably this would be incorrect if we had fetches but
2347 * no dispatches (due to oversized messages, etc.)
2350 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2355 if (ok != 0 && ok != PS_SOCKET)
2356 (protocol->logout_cmd)(sock, ctl);
2360 msg = (char *)NULL; /* sacrifice to -Wall */
2367 msg = "authorization";
2370 msg = "missing or bad RFC822 header";
2376 msg = "client/server synchronization";
2379 msg = "client/server protocol";
2382 msg = "lock busy on server";
2385 msg = "SMTP transaction";
2391 error(0, 0, "undefined");
2394 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2395 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2396 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2397 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2400 /* execute post-initialization command, if any */
2401 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2405 sprintf(buf, "post-connection command failed with status %d", ok);
2407 if (ok == PS_SUCCESS)
2411 signal(SIGALRM, sigsave);
2415 #if defined(HAVE_STDARG_H)
2416 void gen_send(int sock, const char *fmt, ... )
2417 /* assemble command in printf(3) style and send to the server */
2419 void gen_send(sock, fmt, va_alist)
2420 /* assemble command in printf(3) style and send to the server */
2421 int sock; /* socket to which server is connected */
2422 const char *fmt; /* printf-style format */
2426 char buf [MSGBUFSIZE+1];
2429 if (protocol->tagged)
2430 (void) sprintf(buf, "%s ", GENSYM);
2434 #if defined(HAVE_STDARG_H)
2439 #ifdef HAVE_VSNPRINTF
2440 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2442 vsprintf(buf + strlen(buf), fmt, ap);
2446 strcat(buf, "\r\n");
2447 SockWrite(sock, buf, strlen(buf));
2449 if (outlevel == O_VERBOSE)
2453 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2457 sp = cp + strlen(shroud);
2463 buf[strlen(buf)-2] = '\0';
2464 error(0, 0, "%s> %s", protocol->name, buf);
2468 int gen_recv(sock, buf, size)
2469 /* get one line of input from the server */
2470 int sock; /* socket to which server is connected */
2471 char *buf; /* buffer to receive input */
2472 int size; /* length of buffer */
2474 int oldphase = phase; /* we don't have to be re-entrant */
2476 phase = SERVER_WAIT;
2477 set_timeout(mytimeout);
2478 if (SockRead(sock, buf, size) == -1)
2487 if (buf[strlen(buf)-1] == '\n')
2488 buf[strlen(buf)-1] = '\0';
2489 if (buf[strlen(buf)-1] == '\r')
2490 buf[strlen(buf)-1] = '\0';
2491 if (outlevel == O_VERBOSE)
2492 error(0, 0, "%s< %s", protocol->name, buf);
2498 #if defined(HAVE_STDARG_H)
2499 int gen_transact(int sock, char *fmt, ... )
2500 /* assemble command in printf(3) style, send to server, accept a response */
2502 int gen_transact(int sock, fmt, va_alist)
2503 /* assemble command in printf(3) style, send to server, accept a response */
2504 int sock; /* socket to which server is connected */
2505 const char *fmt; /* printf-style format */
2510 char buf [MSGBUFSIZE+1];
2512 int oldphase = phase; /* we don't have to be re-entrant */
2514 phase = SERVER_WAIT;
2516 if (protocol->tagged)
2517 (void) sprintf(buf, "%s ", GENSYM);
2521 #if defined(HAVE_STDARG_H)
2526 #ifdef HAVE_VSNPRINTF
2527 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2529 vsprintf(buf + strlen(buf), fmt, ap);
2533 strcat(buf, "\r\n");
2534 SockWrite(sock, buf, strlen(buf));
2536 if (outlevel == O_VERBOSE)
2540 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2544 sp = cp + strlen(shroud);
2550 buf[strlen(buf)-1] = '\0';
2551 error(0, 0, "%s> %s", protocol->name, buf);
2554 /* we presume this does its own response echoing */
2555 ok = (protocol->parse_response)(sock, buf);
2561 /* driver.c ends here */