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 extern int is_ip_alias();
145 static int is_host_alias(const char *name, struct query *ctl)
146 /* determine whether name is a DNS alias of the hostname */
148 struct hostent *he,*he_st;
149 struct mxentry *mxp, *mxrecords;
151 struct hostdata *lead_server =
152 ctl->server.lead_server ? ctl->server.lead_server : &ctl->server;
155 * The first two checks are optimizations that will catch a good
158 * (1) check against the `true name' deduced from the poll label
159 * and the via option (if present) at the beginning of the poll cycle.
160 * Odds are good this will either be the mailserver's FQDN or a suffix of
161 * it with the mailserver's domain's default host name omitted.
163 * (2) Then check the rest of the `also known as'
164 * cache accumulated by previous DNS checks. This cache is primed
165 * by the aka list option.
167 * Any of these on a mail address is definitive. Only if the
168 * name doesn't match any is it time to call the bind library.
169 * If this happens odds are good we're looking at an MX name.
171 if (strcasecmp(lead_server->truename, name) == 0)
173 else if (str_in_list(&lead_server->akalist, name, TRUE))
175 else if (!ctl->server.dns)
178 #ifndef HAVE_RES_SEARCH
182 * The only code that calls the BIND library is here and in the
183 * start-of-query probe with gethostbyname(3).
185 * We know DNS service was up at the beginning of this poll cycle.
186 * If it's down, our nameserver has crashed. We don't want to try
187 * delivering the current message or anything else from this
188 * mailbox until it's back up.
190 else if ((he = gethostbyname(name)) != (struct hostent *)NULL)
192 if (strcasecmp(ctl->server.truename, he->h_name) == 0)
194 else if (((he_st = gethostbyname(ctl->server.truename)) != (struct hostent *)NULL) && ctl->server.checkalias)
196 if (outlevel == O_VERBOSE)
197 error(0, 0, "Checking if %s is really the same node as %s",ctl->server.truename,name);
198 if (is_ip_alias(ctl->server.truename,name) == TRUE)
200 if (outlevel == O_VERBOSE)
201 error(0, 0, "Yes, their IP addresses match");
204 if (outlevel == O_VERBOSE)
205 error(0, 0, "No, their IP addresses don't match");
213 case HOST_NOT_FOUND: /* specified host is unknown */
214 case NO_ADDRESS: /* valid, but does not have an IP address */
217 case NO_RECOVERY: /* non-recoverable name server error */
218 case TRY_AGAIN: /* temporary error on authoritative server */
220 if (outlevel != O_SILENT)
221 putchar('\n'); /* terminate the progress message */
223 "nameserver failure while looking for `%s' during poll of %s.",
224 name, ctl->server.pollname);
230 * We're only here if DNS was OK but the gethostbyname() failed
231 * with a HOST_NOT_FOUND or NO_ADDRESS error.
232 * Search for a name match on MX records pointing to the server.
235 if ((mxrecords = getmxrecords(name)) == (struct mxentry *)NULL)
239 case HOST_NOT_FOUND: /* specified host is unknown */
240 case NO_ADDRESS: /* valid, but does not have an IP address */
244 case NO_RECOVERY: /* non-recoverable name server error */
245 case TRY_AGAIN: /* temporary error on authoritative server */
248 "nameserver failure while looking for `%s' during poll of %s.",
249 name, ctl->server.pollname);
256 for (mxp = mxrecords; mxp->name; mxp++)
257 if (strcasecmp(ctl->server.truename, mxp->name) == 0)
263 /* add this name to relevant server's `also known as' list */
264 save_str(&lead_server->akalist, name, 0);
266 #endif /* HAVE_RES_SEARCH */
269 static void map_name(name, ctl, xmit_names)
270 /* add given name to xmit_names if it matches declared localnames */
271 const char *name; /* name to map */
272 struct query *ctl; /* list of permissible aliases */
273 struct idlist **xmit_names; /* list of recipient names parsed out */
279 lname = idpair_find(&ctl->localnames, name+off);
280 if (!lname && ctl->wildcard)
283 if (lname != (char *)NULL)
285 if (outlevel == O_VERBOSE)
286 error(0, 0, "mapped %s to local %s", name, lname);
287 save_str(xmit_names, lname, XMIT_ACCEPT);
292 void find_server_names(hdr, ctl, xmit_names)
293 /* parse names out of a RFC822 header into an ID list */
294 const char *hdr; /* RFC822 header in question */
295 struct query *ctl; /* list of permissible aliases */
296 struct idlist **xmit_names; /* list of recipient names parsed out */
298 if (hdr == (char *)NULL)
304 for (cp = nxtaddr(hdr);
311 * If the name of the user begins with a qmail virtual
312 * domain prefix, ignore the prefix. Doing this here
313 * means qvirtual will work either with ordinary name
314 * mapping or with a localdomains option.
316 if (ctl->server.qvirtual)
318 int sl = strlen(ctl->server.qvirtual);
320 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
324 if ((atsign = strchr(cp, '@'))) {
328 * Does a trailing segment of the hostname match something
329 * on the localdomains list? If so, save the whole name
332 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
335 rhs = atsign + (strlen(atsign) - strlen(idp->id));
337 (rhs[-1] == '.' || rhs[-1] == '@') &&
338 strcasecmp(rhs, idp->id) == 0)
340 if (outlevel == O_VERBOSE)
341 error(0, 0, "passed through %s matching %s",
343 save_str(xmit_names, cp, XMIT_ACCEPT);
349 /* if we matched a local domain, idp != NULL */
353 * Check to see if the right-hand part is an alias
354 * or MX equivalent of the mailserver. If it's
355 * not, skip this name. If it is, we'll keep
356 * going and try to find a mapping to a client name.
358 if (!is_host_alias(atsign+1, ctl))
360 save_str(xmit_names, cp, XMIT_REJECT);
366 map_name(cp, ctl, xmit_names);
373 static char *parse_received(struct query *ctl, char *bufp)
374 /* try to extract real address from the Received line */
375 /* If a valid Received: line is found, we return the full address in
376 * a buffer which can be parsed from nxtaddr(). This is to ansure that
377 * the local domain part of the address can be passed along in
378 * find_server_names() if it contains one.
379 * Note: We should return a dummy header containing the address
380 * which makes nxtaddr() behave correctly.
383 char *ok = (char *)NULL;
384 static char rbuf[HOSTLEN + USERNAMELEN + 4];
387 * Try to extract the real envelope addressee. We look here
388 * specifically for the mailserver's Received line.
389 * Note: this will only work for sendmail, or an MTA that
390 * shares sendmail's convention for embedding the envelope
391 * address in the Received line. Sendmail itself only
392 * does this when the mail has a single recipient.
394 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
398 /* extract space-delimited token after "by " */
399 for (sp = ok + 3; isspace(*sp); sp++)
402 for (; !isspace(*sp); sp++)
407 * If it's a DNS name of the mail server, look for the
408 * recipient name after a following "for". Otherwise
411 if (is_host_alias(rbuf, ctl) &&
412 (ok = strstr(sp, "for ")) &&
417 *tp++ = ':'; /* Here is the hack. This is to be friend */
418 *tp++ = ' '; /* with nxtaddr()... */
421 while (*sp == '@') /* skip routes */
422 while (*sp && *sp++ != ':')
424 while (*sp && *sp != '>' && *sp != ';')
429 /* uh oh -- whitespace here can't be right! */
435 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
445 if (outlevel == O_VERBOSE) {
446 char *lf = rbuf + strlen(rbuf)-1;
448 error(0, 0, "found Received address `%s'", rbuf+2);
455 static int smtp_open(struct query *ctl)
456 /* try to open a socket to the appropriate SMTP server for this query */
458 /* maybe it's time to close the socket in order to force delivery */
459 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
461 close(ctl->smtp_socket);
462 ctl->smtp_socket = -1;
466 /* if no socket to any SMTP host is already set up, try to open one */
467 if (ctl->smtp_socket == -1)
470 * RFC 1123 requires that the domain name in HELO address is a
471 * "valid principal domain name" for the client host. If we're
472 * running in invisible mode, violate this with malice
473 * aforethought in order to make the Received headers and
474 * logging look right.
476 * In fact this code relies on the RFC1123 requirement that the
477 * SMTP listener must accept messages even if verification of the
478 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
480 * How we compute the true mailhost name to pass to the
481 * listener doesn't affect behavior on RFC1123- violating
482 * listener that check for name match; we're going to lose
483 * on those anyway because we can never give them a name
484 * that matches the local machine fetchmail is running on.
485 * What it will affect is the listener's logging.
488 char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
489 int oldphase = phase;
494 * Run down the SMTP hunt list looking for a server that's up.
495 * Use both explicit hunt entries (value TRUE) and implicit
496 * (default) ones (value FALSE).
499 phase = LISTENER_WAIT;
501 set_timeout(ctl->server.timeout);
502 for (idp = ctl->smtphunt; idp; idp = idp->next)
504 char *cp, *parsed_host = alloca(strlen(idp->id) + 1);
506 char *portnum = SMTP_PORT;
508 int portnum = SMTP_PORT;
511 ctl->smtphost = idp->id; /* remember last host tried. */
513 strcpy(parsed_host, idp->id);
514 if ((cp = strrchr(parsed_host, '/')))
524 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
527 /* first, probe for ESMTP */
528 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
529 SMTP_ehlo(ctl->smtp_socket, id_me,
530 &ctl->server.esmtp_options) == SM_OK)
534 * RFC 1869 warns that some listeners hang up on a failed EHLO,
535 * so it's safest not to assume the socket will still be good.
537 close(ctl->smtp_socket);
538 ctl->smtp_socket = -1;
540 /* if opening for ESMTP failed, try SMTP */
541 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
544 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
545 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
548 close(ctl->smtp_socket);
549 ctl->smtp_socket = -1;
555 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
556 error(0, 0, "forwarding to %s", ctl->smtphost);
558 return(ctl->smtp_socket);
561 /* these are shared by stuffline, readheaders and readbody */
563 static RETSIGTYPE (*sigchld)();
564 static int sizeticker;
566 static int stuffline(struct query *ctl, char *buf)
567 /* ship a line to the given control block's output sink (SMTP server or MDA) */
572 /* The line may contain NUL characters. Find the last char to use
573 * -- the real line termination is the sequence "\n\0".
576 while ((last += strlen(last)) && (last[-1] != '\n'))
579 /* fix message lines that have only \n termination (for qmail) */
582 if (last - 1 == buf || last[-2] != '\r')
591 phase = FORWARDING_WAIT;
594 * SMTP byte-stuffing. We only do this if the protocol does *not*
595 * use .<CR><LF> as EOM. If it does, the server will already have
596 * decorated any . lines it sends back up.
599 if (protocol->delimited) /* server has already byte-stuffed */
604 /* writing to SMTP, leave the byte-stuffing in place */;
606 else /* if (!protocol->delimited) -- not byte-stuffed already */
609 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
611 /* leave it alone */;
614 /* we may need to strip carriage returns */
619 for (sp = tp = buf; sp < last; sp++)
628 n = fwrite(buf, 1, last - buf, sinkfp);
629 else if (ctl->smtp_socket != -1)
630 n = SockWrite(ctl->smtp_socket, buf, last - buf);
638 static void sanitize(s)
639 /* replace unsafe shellchars by an _ */
642 static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
645 for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
650 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
652 static int readheaders(sock, fetchlen, reallen, ctl, num)
653 /* read message headers and ship to SMTP or MDA */
654 int sock; /* to which the server is connected */
655 long fetchlen; /* length of message according to fetch response */
656 long reallen; /* length of message according to getsizes */
657 struct query *ctl; /* query control record */
658 int num; /* index of message */
663 struct addrblk *next;
665 struct addrblk *to_addrchain = NULL;
666 struct addrblk **to_chainptr = &to_addrchain;
667 struct addrblk *resent_to_addrchain = NULL;
668 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
670 char buf[MSGBUFSIZE+1];
671 char return_path[HOSTLEN + USERNAMELEN + 4];
672 int from_offs, reply_to_offs, resent_from_offs;
673 int app_from_offs, sender_offs, resent_sender_offs;
675 char *headers, *received_for, *destaddr, *rcv, *cp;
676 int n, linelen, oldlen, ch, remaining, skipcount;
677 struct idlist *idp, *xmit_names;
678 flag good_addresses, bad_addresses, has_nuls;
679 flag no_local_matches = FALSE;
684 has_nuls = headers_ok = FALSE;
685 return_path[0] = '\0';
686 olderrs = ctl->errcount;
688 /* read message headers */
689 headers = received_for = NULL;
690 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
691 sender_offs = resent_sender_offs = env_offs = -1;
697 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
701 line = xmalloc(sizeof(buf));
705 set_timeout(ctl->server.timeout);
706 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
716 /* lines may not be properly CRLF terminated; fix this for qmail */
719 cp = buf + strlen(buf) - 1;
720 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
729 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
733 /* check for end of headers */
737 has_nuls = (linelen != strlen(line));
739 goto process_headers;
743 * Check for end of message immediately. If one of your folders
744 * has been mangled, the delimiter may occur directly after the
747 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
750 has_nuls = (linelen != strlen(line));
751 goto process_headers;
754 /* we may need to grab RFC822 continuations */
755 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
757 /* write the message size dots */
758 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
760 sizeticker += linelen;
761 while (sizeticker >= SIZETICKER)
764 sizeticker -= SIZETICKER;
768 /* we see an ordinary (non-header, non-message-delimiter line */
769 has_nuls = (linelen != strlen(line));
772 * The University of Washington IMAP server (the reference
773 * implementation of IMAP4 written by Mark Crispin) relies
774 * on being able to keep base-UID information in a special
775 * message at the head of the mailbox. This message should
776 * neither be deleted nor forwarded.
780 * We disable this check under POP2 because there's no way to
781 * prevent deletion of the message. So at least we ought to
782 * forward it to the user so he or she will have some clue
783 * that things have gone awry.
785 if (protocol->port != 109)
786 #endif /* POP2_ENABLE */
787 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
794 * This code prevents fetchmail from becoming an accessory after
795 * the fact to upstream sendmails with the `E' option on. This
796 * can result in an escaped Unix From_ line at the beginning of
797 * the headers. If fetchmail just passes it through, the client
798 * listener may think the message has *no* headers (since the first)
799 * line it sees doesn't look RFC822-conformant) and fake up a set.
801 * What the user would see in this case is bogus (synthesized)
802 * headers, followed by a blank line, followed by the >From,
803 * followed by the real headers, followed by a blank line,
806 * We forestall this lossage by tossing anything that looks
807 * like an escaped From_ line in headers. These aren't RFC822
808 * so our conscience is clear...
810 if (!strncasecmp(line, ">From ", 6))
817 * If we see a Status line, it may have been inserted by an MUA
818 * on the mail host, or it may have been inserted by the server
819 * program after the headers in the transaction stream. This
820 * can actually hose some new-mail notifiers such as xbuffy,
821 * which assumes any Status line came from a *local* MDA and
822 * therefore indicates that the message has been seen.
824 * Some buggy POP servers (including at least the 3.3(20)
825 * version of the one distributed with IMAP) insert empty
826 * Status lines in the transaction stream; we'll chuck those
827 * unconditionally. Nonempty ones get chucked if the user
828 * turns on the dropstatus flag.
832 if (!strncasecmp(line, "Status:", 7))
834 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
839 while (*cp && isspace(*cp)) cp++;
840 if (!*cp || ctl->dropstatus)
849 line = reply_hack(line, ctl->server.truename);
852 * OK, this is messy. If we're forwarding by SMTP, it's the
853 * SMTP-receiver's job (according to RFC821, page 22, section
854 * 4.1.1) to generate a Return-Path line on final delivery.
855 * The trouble is, we've already got one because the
856 * mailserver's SMTP thought *it* was responsible for final
859 * Stash away the contents of Return-Path for use in generating
860 * MAIL FROM later on, then prevent the header from being saved
861 * with the others. In effect, we strip it off here.
863 * If the SMTP server conforms to the standards, and fetchmail gets the
864 * envelope sender from the Return-Path, the new Return-Path should be
865 * exactly the same as the original one.
867 * We do *not* want to ignore empty Return-Path headers. These should
868 * be passed through as a way of indicating that a message should
869 * not trigger bounces if delivery fails. What we *do* need to do is
870 * make sure we never try to rewrite such a blank Return-Path. We
871 * handle this with a check for <> in the rewrite logic.
873 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
875 strcpy(return_path, cp);
884 oldlen = strlen(line);
885 headers = xmalloc(oldlen + 1);
886 (void) strcpy(headers, line);
894 newlen = oldlen + strlen(line);
895 headers = (char *) realloc(headers, newlen + 1);
896 if (headers == NULL) {
900 strcpy(headers + oldlen, line);
902 line = headers + oldlen;
906 if (!strncasecmp("From:", line, 5))
907 from_offs = (line - headers);
908 else if (!strncasecmp("Reply-To:", line, 9))
909 reply_to_offs = (line - headers);
910 else if (!strncasecmp("Resent-From:", line, 12))
911 resent_from_offs = (line - headers);
912 else if (!strncasecmp("Apparently-From:", line, 16))
913 app_from_offs = (line - headers);
914 else if (!strncasecmp("Sender:", line, 7))
915 sender_offs = (line - headers);
916 else if (!strncasecmp("Resent_Sender:", line, 14))
917 resent_sender_offs = (line - headers);
919 else if (!strncasecmp("Message-Id:", buf, 11))
921 if (ctl->server.uidl)
925 buf[IDLEN+12] = 0; /* prevent stack overflow */
926 sscanf(buf+12, "%s", id);
927 if (!str_find( &ctl->newsaved, num))
929 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
930 new->val.status.num = num;
935 else if (!MULTIDROP(ctl))
938 else if (!strncasecmp("To:", line, 3)
939 || !strncasecmp("Cc:", line, 3)
940 || !strncasecmp("Bcc:", line, 4)
941 || !strncasecmp("Apparently-To:", line, 14))
943 *to_chainptr = xmalloc(sizeof(struct addrblk));
944 (*to_chainptr)->offset = (line - headers);
945 to_chainptr = &(*to_chainptr)->next;
949 else if (!strncasecmp("Resent-To:", line, 10)
950 || !strncasecmp("Resent-Cc:", line, 10)
951 || !strncasecmp("Resent-Bcc:", line, 11))
953 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
954 (*resent_to_chainptr)->offset = (line - headers);
955 resent_to_chainptr = &(*resent_to_chainptr)->next;
956 *resent_to_chainptr = NULL;
959 else if (ctl->server.envelope != STRING_DISABLED)
961 if (ctl->server.envelope
962 && strcasecmp(ctl->server.envelope, "Received"))
964 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
966 strlen(ctl->server.envelope)))
968 if (skipcount++ != ctl->server.envskip)
970 env_offs = (line - headers);
973 else if (!received_for && !strncasecmp("Received:", line, 9))
975 if (skipcount++ != ctl->server.envskip)
977 received_for = parse_received(ctl, line);
984 * We want to detect this early in case there are so few headers that the
985 * dispatch logic barfs.
989 if (outlevel > O_SILENT)
990 error(0,0,"message delimiter found while scanning headers");
994 * Hack time. If the first line of the message was blank, with no headers
995 * (this happens occasionally due to bad gatewaying software) cons up
996 * a set of fake headers.
998 * If you modify the fake header template below, be sure you don't
999 * make either From or To address @-less, otherwise the reply_hack
1000 * logic will do bad things.
1002 if (headers == (char *)NULL)
1004 #ifdef HAVE_SNPRINTF
1005 snprintf(buf, sizeof(buf),
1008 #endif /* HAVE_SNPRINTF */
1009 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
1010 fetchmailhost, user, ctl->remotename, ctl->server.truename);
1011 headers = xstrdup(buf);
1015 * We can now process message headers before reading the text.
1016 * In fact we have to, as this will tell us where to forward to.
1019 /* Decode MIME encoded headers. We MUST do this before
1020 * looking at the Content-Type / Content-Transfer-Encoding
1021 * headers (RFC 2046).
1023 if (ctl->mimedecode) {
1024 UnMimeHeader(headers);
1026 /* Check for MIME headers indicating possible 8-bit data */
1027 mimemsg = MimeBodyType(headers, ctl->mimedecode);
1030 * If there is a Return-Path address on the message, this was
1031 * almost certainly the MAIL FROM address given the originating
1032 * sendmail. This is the best thing to use for logging the
1033 * message origin (it sets up the right behavior for bounces and
1034 * mailing lists). Otherwise, fall down to the next available
1035 * envelope address (which is the most probable real sender).
1036 * *** The order is important! ***
1037 * This is especially useful when receiving mailing list
1038 * messages in multidrop mode. if a local address doesn't
1039 * exist, the bounce message won't be returned blindly to the
1040 * author or to the list itself but rather to the list manager
1041 * (ex: specified by "Sender:") wich is less anoying. This is
1042 * true for most mailing list packages.
1044 if( !return_path[0] ){
1046 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
1047 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
1048 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
1049 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
1050 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
1051 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
1052 if (ap) strcpy( return_path, ap );
1055 /* cons up a list of local recipients */
1056 xmit_names = (struct idlist *)NULL;
1057 bad_addresses = good_addresses = accept_count = reject_count = 0;
1058 /* is this a multidrop box? */
1061 if (env_offs > -1) /* We have the actual envelope addressee */
1062 find_server_names(headers + env_offs, ctl, &xmit_names);
1063 else if (received_for)
1065 * We have the Received for addressee.
1066 * It has to be a mailserver address, or we
1067 * wouldn't have got here.
1068 * We use find_server_names() to let local
1069 * hostnames go through.
1071 find_server_names(received_for, ctl, &xmit_names);
1074 * We haven't extracted the envelope address.
1075 * So check all the "Resent-To" header addresses if
1076 * they exist. If and only if they don't, consider
1077 * the "To" adresses.
1079 register struct addrblk *nextptr;
1080 if (resent_to_addrchain) {
1081 /* delete the "To" chain and substitute it
1082 * with the "Resent-To" list
1084 while (to_addrchain) {
1085 nextptr = to_addrchain->next;
1087 to_addrchain = nextptr;
1089 to_addrchain = resent_to_addrchain;
1090 resent_to_addrchain = NULL;
1092 /* now look for remaining adresses */
1093 while (to_addrchain) {
1094 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
1095 nextptr = to_addrchain->next;
1097 to_addrchain = nextptr;
1102 no_local_matches = TRUE;
1103 save_str(&xmit_names, user, XMIT_ACCEPT);
1104 if (outlevel == O_VERBOSE)
1106 "no local matches, forwarding to %s",
1110 else /* it's a single-drop box, use first localname */
1111 save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
1115 * Time to either address the message or decide we can't deliver it yet.
1117 if (ctl->errcount > olderrs) /* there were DNS errors above */
1119 if (outlevel == O_VERBOSE)
1120 error(0,0, "forwarding and deletion suppressed due to DNS errors");
1122 free_str_list(&xmit_names);
1123 return(PS_TRANSIENT);
1125 else if (ctl->mda) /* we have a declared MDA */
1127 int length = 0, fromlen = 0, nameslen = 0;
1128 char *names = NULL, *before, *after, *from = NULL;
1130 for (idp = xmit_names; idp; idp = idp->next)
1131 if (idp->val.status.mark == XMIT_ACCEPT)
1134 destaddr = "localhost";
1136 length = strlen(ctl->mda);
1137 before = xstrdup(ctl->mda);
1139 /* get user addresses for %T (or %s for backward compatibility) */
1140 if (strstr(before, "%s") || strstr(before, "%T"))
1143 * We go through this in order to be able to handle very
1144 * long lists of users and (re)implement %s.
1147 for (idp = xmit_names; idp; idp = idp->next)
1148 if (idp->val.status.mark == XMIT_ACCEPT)
1149 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1151 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1153 for (idp = xmit_names; idp; idp = idp->next)
1154 if (idp->val.status.mark == XMIT_ACCEPT)
1156 strcat(names, idp->id);
1159 names[--nameslen] = '\0'; /* chop trailing space */
1161 /* sanitize names in order to contain *only* harmless shell chars */
1165 /* get From address for %F */
1166 if (strstr(before, "%F"))
1168 from = xstrdup(return_path);
1170 /* sanitize from in order to contain *only* harmless shell chars */
1173 fromlen = strlen(from);
1176 /* do we have to build an mda string? */
1177 if (names || from) {
1182 /* find length of resulting mda string */
1184 while (sp = strstr(sp, "%s")) {
1185 length += nameslen - 2; /* subtract %s */
1189 while (sp = strstr(sp, "%T")) {
1190 length += nameslen - 2; /* subtract %T */
1194 while (sp = strstr(sp, "%F")) {
1195 length += fromlen - 2; /* subtract %F */
1199 after = xmalloc(length + 1);
1201 /* copy mda source string to after, while expanding %[sTF] */
1202 for (dp = after, sp = before; *dp = *sp; dp++, sp++) {
1203 if (sp[0] != '%') continue;
1205 /* need to expand? BTW, no here overflow, because in
1206 ** the worst case (end of string) sp[1] == '\0' */
1207 if (sp[1] == 's' || sp[1] == 'T') {
1210 sp++; /* position sp over [sT] */
1211 dp--; /* adjust dp */
1212 } else if (sp[1] == 'F') {
1215 sp++; /* position sp over F */
1216 dp--; /* adjust dp */
1235 if (outlevel == O_VERBOSE)
1236 error(0, 0, "about to deliver with: %s", before);
1240 * Arrange to run with user's permissions if we're root.
1241 * This will initialize the ownership of any files the
1242 * MDA creates properly. (The seteuid call is available
1243 * under all BSDs and Linux)
1246 #endif /* HAVE_SETEUID */
1248 sinkfp = popen(before, "w");
1253 /* this will fail quietly if we didn't start as root */
1255 #endif /* HAVE_SETEUID */
1259 error(0, 0, "MDA open failed");
1261 free_str_list(&xmit_names);
1265 sigchld = signal(SIGCHLD, SIG_DFL);
1269 char *ap, options[MSGBUFSIZE], addr[128];
1271 /* build a connection to the SMTP listener */
1272 if ((smtp_open(ctl) == -1))
1274 error(0, errno, "SMTP connect to %s failed",
1275 ctl->smtphost ? ctl->smtphost : "localhost");
1277 free_str_list(&xmit_names);
1282 * Compute ESMTP options.
1285 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
1286 if (ctl->pass8bits || (mimemsg & MSG_IS_8BIT))
1287 strcpy(options, " BODY=8BITMIME");
1288 else if (mimemsg & MSG_IS_7BIT)
1289 strcpy(options, " BODY=7BIT");
1292 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1293 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1296 * Try to get the SMTP listener to take the Return-Path
1297 * address as MAIL FROM . If it won't, fall back on the
1298 * calling-user ID. This won't affect replies, which use the
1299 * header From address anyway.
1301 * RFC 1123 requires that the domain name part of the
1302 * MAIL FROM address be "canonicalized", that is a
1303 * FQDN or MX but not a CNAME. We'll assume the From
1304 * header is already in this form here (it certainly
1305 * is if rewrite is on). RFC 1123 is silent on whether
1306 * a nonexistent hostname part is considered canonical.
1308 * This is a potential problem if the MTAs further upstream
1309 * didn't pass canonicalized From/Return-Path lines, *and* the
1310 * local SMTP listener insists on them.
1312 * None of these error conditions generates bouncemail. Comments
1313 * below explain for each case why this is so.
1315 ap = (return_path[0]) ? return_path : user;
1316 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1318 int smtperr = atoi(smtp_response);
1320 if (smtperr == ctl->antispam)
1323 * SMTP listener explicitly refuses to deliver mail
1324 * coming from this address, probably due to an
1325 * anti-spam domain exclusion. Respect this. Don't
1326 * try to ship the message, and don't prevent it from
1327 * being deleted. Typical values:
1329 * 571 = sendmail's "unsolicited email refused"
1330 * 501 = exim's old antispam response
1331 * 550 = exim's new antispam response (temporary)
1333 * We don't send bouncemail on antispam failures because
1334 * we don't want the scumbags to know the address is even
1337 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1339 free_str_list(&xmit_names);
1344 * Suppress error message only if the response specifically
1345 * meant `excluded for policy reasons'. We *should* see
1346 * an error when the return code is less specific.
1349 error(0, -1, "SMTP error: %s", smtp_response);
1353 case 452: /* insufficient system storage */
1355 * Temporary out-of-queue-space condition on the
1356 * ESMTP server. Don't try to ship the message,
1357 * and suppress deletion so it can be retried on
1358 * a future retrieval cycle.
1360 * Bouncemail *might* be appropriate here as a delay
1361 * notification. But it's not really necessary because
1362 * this is not an actual failure, we're very likely to be
1363 * able to recover on the next cycle.
1365 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1367 free_str_list(&xmit_names);
1368 return(PS_TRANSIENT);
1370 case 552: /* message exceeds fixed maximum message size */
1371 case 553: /* invalid sending domain */
1373 * Permanent no-go condition on the
1374 * ESMTP server. Don't try to ship the message,
1375 * and allow it to be deleted.
1377 * Bouncemail would be appropriate for 552, but in these
1378 * latter days 553 usually means a spammer is trying to
1379 * cover his tracks. We'd rather deny the scumbags any
1380 * feedback that the address is valid.
1382 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1384 free_str_list(&xmit_names);
1387 default: /* retry with invoking user's address */
1388 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1390 error(0, -1, "SMTP error: %s", smtp_response);
1392 free_str_list(&xmit_names);
1393 return(PS_SMTP); /* should never happen */
1399 * Now list the recipient addressees
1401 * RFC 1123 requires that the domain name part of the
1402 * RCPT TO address be "canonicalized", that is a FQDN
1403 * or MX but not a CNAME. Some listeners (like exim)
1406 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1408 for (idp = xmit_names; idp; idp = idp->next)
1409 if (idp->val.status.mark == XMIT_ACCEPT)
1411 if (strchr(idp->id, '@'))
1412 strcpy(addr, idp->id);
1414 #ifdef HAVE_SNPRINTF
1415 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1417 sprintf(addr, "%s@%s", idp->id, destaddr);
1418 #endif /* HAVE_SNPRINTF */
1420 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1425 idp->val.status.mark = XMIT_ANTISPAM;
1427 "SMTP listener doesn't like recipient address `%s'",
1431 if (!good_addresses)
1433 #ifdef HAVE_SNPRINTF
1434 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1436 sprintf(addr, "%s@%s", user, destaddr);
1437 #endif /* HAVE_SNPRINTF */
1439 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1441 error(0, 0, "can't even send to calling user!");
1443 free_str_list(&xmit_names);
1448 /* tell it we're ready to send data */
1449 SMTP_data(ctl->smtp_socket);
1454 * Some server/sendmail combinations cause problems when our
1455 * synthetic Received line is before the From header. Cope
1458 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1463 n = stuffline(ctl, headers);
1466 if (!run.invisible && n != -1)
1468 /* utter any per-message Received information we need here */
1469 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1470 n = stuffline(ctl, buf);
1474 * We used to include ctl->remotename in this log line,
1475 * but this can be secure information that would be bad
1478 sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1482 n = stuffline(ctl, buf);
1488 if (good_addresses == 0)
1491 "for <%s@%s> (by default); ",
1494 else if (good_addresses == 1)
1496 for (idp = xmit_names; idp; idp = idp->next)
1497 if (idp->val.status.mark == XMIT_ACCEPT)
1498 break; /* only report first address */
1499 if (strchr(idp->id, '@'))
1500 sprintf(buf+1, "for <%s>", idp->id);
1502 sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1503 sprintf(buf+strlen(buf), " (%s); ",
1504 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1510 #ifdef HAVE_STRFTIME
1512 * Conform to RFC822. This is typically going to emit
1513 * a three-letter timezone for %Z, which is going to
1514 * be marked "obsolete syntax" in 822bis. Note that we
1515 * generate a 4-digit year here.
1517 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1518 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1521 * This is really just a portability fallback, as the
1522 * date format ctime(3) emits is not RFC822
1525 strcat(buf, ctime(&now));
1526 #endif /* HAVE_STRFTIME */
1527 n = stuffline(ctl, buf);
1533 n = stuffline(ctl, rcv); /* ship out rest of headers */
1537 error(0, errno, "writing RFC822 headers");
1542 signal(SIGCHLD, sigchld);
1545 free_str_list(&xmit_names);
1548 else if (outlevel == O_VERBOSE)
1551 /* write error notifications */
1552 if (no_local_matches || has_nuls || bad_addresses)
1555 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1558 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1559 if (no_local_matches)
1561 if (reject_count != 1)
1562 strcat(errhd, "no recipient addresses matched declared local names");
1565 for (idp = xmit_names; idp; idp = idp->next)
1566 if (idp->val.status.mark == XMIT_REJECT)
1568 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1574 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1575 strcat(errhd, "; ");
1576 strcat(errhd, "message has embedded NULs");
1581 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1582 strcat(errhd, "; ");
1583 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1584 errlen = strlen(errhd);
1585 for (idp = xmit_names; idp; idp = idp->next)
1586 if (idp->val.status.mark == XMIT_ANTISPAM)
1587 errlen += strlen(idp->id) + 2;
1589 errmsg = alloca(errlen+3);
1590 (void) strcpy(errmsg, errhd);
1591 for (idp = xmit_names; idp; idp = idp->next)
1592 if (idp->val.status.mark == XMIT_ANTISPAM)
1594 strcat(errmsg, idp->id);
1596 strcat(errmsg, ", ");
1601 strcat(errmsg, "\n");
1603 /* ship out the error line */
1605 stuffline(ctl, errmsg);
1608 /* issue the delimiter line */
1613 stuffline(ctl, buf);
1616 free_str_list(&xmit_names);
1617 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1620 static int readbody(sock, ctl, forward, len)
1621 /* read and dispose of a message body presented on sock */
1622 struct query *ctl; /* query control record */
1623 int sock; /* to which the server is connected */
1624 int len; /* length of message */
1625 flag forward; /* TRUE to forward */
1628 unsigned char buf[MSGBUFSIZE+1];
1629 unsigned char *inbufp = buf;
1630 flag issoftline = FALSE;
1632 /* pass through the text lines */
1633 while (protocol->delimited || len > 0)
1635 set_timeout(ctl->server.timeout);
1636 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-1-(inbufp-buf)))==-1)
1643 signal(SIGCHLD, sigchld);
1649 /* write the message size dots */
1652 sizeticker += linelen;
1653 while (sizeticker >= SIZETICKER)
1655 if (outlevel > O_SILENT)
1657 sizeticker -= SIZETICKER;
1662 /* check for end of message */
1663 if (protocol->delimited && *inbufp == '.')
1664 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1666 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1669 msglen--; /* subtract the size of the dot escape */
1673 if (ctl->mimedecode && (mimemsg & MSG_NEEDS_DECODE)) {
1674 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1675 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1678 * Soft linebreak, but less than 200 bytes left in
1679 * input buffer. Rather than doing a buffer overrun,
1680 * ignore the soft linebreak, NL-terminate data and
1681 * deliver what we have now.
1682 * (Who writes lines longer than 2K anyway?)
1684 *inbufp = '\n'; *(inbufp+1) = '\0';
1689 /* ship out the text line */
1690 if (forward && (!issoftline))
1692 int n = stuffline(ctl, buf);
1697 error(0, errno, "writing message text");
1702 signal(SIGCHLD, sigchld);
1706 else if (outlevel == O_VERBOSE)
1716 kerberos_auth (socket, canonical)
1717 /* authenticate to the server host using Kerberos V4 */
1718 int socket; /* socket to server host */
1720 char *canonical; /* server name */
1722 const char *canonical; /* server name */
1725 char * host_primary;
1729 Key_schedule schedule;
1732 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1733 rem = (krb_sendauth (0L, socket, ticket, "pop",
1735 ((char *) (krb_realmofhost (canonical))),
1736 ((unsigned long) 0),
1740 ((struct sockaddr_in *) 0),
1741 ((struct sockaddr_in *) 0),
1744 if (rem != KSUCCESS)
1746 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1747 return (PS_AUTHFAIL);
1751 #endif /* KERBEROS_V4 */
1755 kerberos5_auth(socket, canonical)
1756 /* authernticate to the server host using Kerberos V5 */
1757 int socket; /* socket to server host */
1758 const char *canonical; /* server name */
1760 krb5_error_code retval;
1761 krb5_context context;
1763 krb5_principal client = NULL, server = NULL;
1764 krb5_error *err_ret = NULL;
1766 krb5_auth_context auth_context = NULL;
1768 krb5_init_context(&context);
1769 krb5_init_ets(context);
1770 krb5_auth_con_init(context, &auth_context);
1772 if (retval = krb5_cc_default(context, &ccdef)) {
1773 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1777 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1778 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1782 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1785 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1789 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1790 "KPOPV1.0", client, server,
1791 AP_OPTS_MUTUAL_REQUIRED,
1792 NULL, /* no data to checksum */
1793 0, /* no creds, use ccache instead */
1797 NULL); /* don't need reply */
1799 krb5_free_principal(context, server);
1800 krb5_free_principal(context, client);
1801 krb5_auth_con_free(context, auth_context);
1804 if (err_ret && err_ret->text.length) {
1805 error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1806 error_message(retval),
1807 err_ret->text.length,
1808 err_ret->text.data);
1809 krb5_free_error(context, err_ret);
1811 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1817 #endif /* KERBEROS_V5 */
1819 int do_protocol(ctl, proto)
1820 /* retrieve messages from server using given protocol method table */
1821 struct query *ctl; /* parsed options with merged-in defaults */
1822 const struct method *proto; /* protocol method table */
1824 int ok, js, sock = -1;
1829 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1831 error(0, -1, "Kerberos V4 support not linked.");
1834 #endif /* KERBEROS_V4 */
1837 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1839 error(0, -1, "Kerberos V5 support not linked.");
1842 #endif /* KERBEROS_V5 */
1844 /* lacking methods, there are some options that may fail */
1847 /* check for unsupported options */
1850 "Option --flush is not supported with %s",
1854 else if (ctl->fetchall) {
1856 "Option --all is not supported with %s",
1861 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1864 "Option --limit is not supported with %s",
1872 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1875 /* set up the server-nonresponse timeout */
1876 sigsave = signal(SIGALRM, timeout_handler);
1877 mytimeout = ctl->server.timeout;
1879 if ((js = setjmp(restart)) == 1)
1881 if (phase == SERVER_WAIT)
1883 "timeout after %d seconds waiting for server %s.",
1884 ctl->server.timeout, ctl->server.pollname);
1885 else if (phase == FORWARDING_WAIT)
1887 "timeout after %d seconds waiting for %s.",
1888 ctl->server.timeout,
1889 ctl->mda ? "MDA" : "SMTP");
1890 else if (phase == LISTENER_WAIT)
1892 "timeout after %d seconds waiting for listener to respond.");
1894 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1896 if (ctl->smtp_socket != -1)
1897 close(ctl->smtp_socket);
1906 char buf [POPBUFSIZE+1], *realhost;
1907 int *msgsizes, len, num, count, new, bytes, deletions = 0;
1909 int fetches, dispatches;
1911 int port, fetches, dispatches;
1915 /* execute pre-initialization command, if any */
1916 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1918 sprintf(buf, "pre-connection command failed with status %d", ok);
1924 /* open a socket to the mail server */
1926 port = ctl->server.port ? ctl->server.port : protocol->port;
1928 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1930 if ((sock = SockOpen(realhost,
1931 ctl->server.service ? ctl->server.service : protocol->service,
1932 ctl->server.netsec)) == -1)
1934 if ((sock = SockOpen(realhost, port, NULL)) == -1)
1938 #ifndef EHOSTUNREACH
1939 #define EHOSTUNREACH (-1)
1941 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1943 error_build("fetchmail: %s connection to %s failed: ",
1944 protocol->name, ctl->server.pollname);
1945 #ifdef HAVE_RES_SEARCH
1946 if (h_errno == HOST_NOT_FOUND)
1947 error_complete(0, 0, "host is unknown");
1948 else if (h_errno == NO_ADDRESS)
1949 error_complete(0, 0, "name is valid but has no IP address");
1950 else if (h_errno == NO_RECOVERY)
1951 error_complete(0, 0, "unrecoverable name server error");
1952 else if (h_errno == TRY_AGAIN)
1953 error_complete(0, 0, "temporary name server error");
1955 error_complete(0, 0, "unknown DNS error %d", h_errno);
1957 #endif /* HAVE_RES_SEARCH */
1958 error_complete(0, errno, "local error");
1966 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1968 set_timeout(ctl->server.timeout);
1969 ok = kerberos_auth(sock, ctl->server.truename);
1974 #endif /* KERBEROS_V4 */
1977 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1979 set_timeout(ctl->server.timeout);
1980 ok = kerberos5_auth(sock, ctl->server.truename);
1985 #endif /* KERBEROS_V5 */
1987 /* accept greeting message from mail server */
1988 ok = (protocol->parse_response)(sock, buf);
1992 /* try to get authorized to fetch mail */
1993 if (protocol->getauth)
1995 if (protocol->password_canonify)
1996 (protocol->password_canonify)(shroud, ctl->password);
1998 strcpy(shroud, ctl->password);
2000 ok = (protocol->getauth)(sock, ctl, buf);
2003 if (ok == PS_LOCKBUSY)
2004 error(0, -1, "Lock-busy error on %s@%s",
2006 ctl->server.truename);
2011 error(0, -1, "Authorization failure on %s@%s",
2013 ctl->server.truename);
2019 ctl->errcount = fetches = 0;
2021 /* now iterate over each folder selected */
2022 for (idp = ctl->mailboxes; idp; idp = idp->next)
2029 if (outlevel >= O_VERBOSE)
2031 error(0, 0, "selecting or re-polling folder %s", idp->id);
2033 error(0, 0, "selecting or re-polling default folder");
2035 /* compute # of messages and number of new messages waiting */
2036 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
2041 * We need the size of each message before it's
2042 * loaded in order to pass via the ESMTP SIZE
2043 * option. If the protocol has a getsizes method,
2044 * we presume this means it doesn't get reliable
2045 * sizes from message fetch responses.
2047 if (count > 0 && proto->getsizes)
2051 msgsizes = (int *)alloca(sizeof(int) * count);
2052 for (i = 0; i < count; i++)
2055 ok = (proto->getsizes)(sock, count, msgsizes);
2062 for (i = 0; i < count; i++)
2063 bytes += msgsizes[i];
2067 /* show user how many messages we downloaded */
2069 (void) sprintf(buf, "%s at %s (folder %s)",
2070 ctl->remotename, ctl->server.truename, idp->id);
2072 (void) sprintf(buf, "%s at %s",
2073 ctl->remotename, ctl->server.truename);
2074 if (outlevel > O_SILENT)
2075 if (count == -1) /* only used for ETRN */
2076 error(0, 0, "Polling %s", ctl->server.truename);
2077 else if (count != 0)
2079 if (new != -1 && (count - new) > 0)
2080 error_build("%d message%s (%d seen) for %s",
2081 count, count > 1 ? "s" : "", count-new, buf);
2083 error_build("%d message%s for %s",
2084 count, count > 1 ? "s" : "", buf);
2086 error_complete(0, 0, ".");
2088 error_complete(0, 0, " (%d bytes).", bytes);
2092 /* these are pointless in normal daemon mode */
2093 if (pass == 1 && (run.poll_interval == 0 || outlevel == O_VERBOSE))
2094 error(0, 0, "No mail for %s", buf);
2097 /* very important, this is where we leave the do loop */
2103 if (new == -1 || ctl->fetchall)
2105 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
2110 flag force_retrieval;
2113 * What forces this code is that in POP2 and
2114 * IMAP2bis you can't fetch a message without
2115 * having it marked `seen'. In POP3 and IMAP4, on the
2116 * other hand, you can (peek_capable is set by
2117 * each driver module to convey this; it's not a
2118 * method constant because of the difference between
2119 * IMAP2bis and IMAP4).
2121 * The result of being unable to peek is that if there's
2122 * any kind of transient error (DNS lookup failure, or
2123 * sendmail refusing delivery due to process-table limits)
2124 * the message will be marked "seen" on the server without
2125 * having been delivered. This is not a big problem if
2126 * fetchmail is running in foreground, because the user
2127 * will see a "skipped" message when it next runs and get
2130 * But in daemon mode this leads to the message
2131 * being silently ignored forever. This is not
2134 * We compensate for this by checking the error
2135 * count from the previous pass and forcing all
2136 * messages to be considered new if it's nonzero.
2138 force_retrieval = !peek_capable && (ctl->errcount > 0);
2140 /* read, forward, and delete messages */
2141 for (num = 1; num <= count; num++)
2143 flag toolarge = NUM_NONZERO(ctl->limit)
2144 && msgsizes && (msgsizes[num-1] > ctl->limit);
2145 flag fetch_it = !toolarge
2146 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
2147 flag suppress_delete = FALSE;
2148 flag suppress_forward = FALSE;
2149 flag suppress_readbody = FALSE;
2150 flag retained = FALSE;
2153 * This check copes with Post Office/NT's
2154 * annoying habit of randomly prepending bogus
2155 * LIST items of length -1. Patrick Audley
2156 * <paudley@pobox.com> tells us: LIST shows a
2157 * size of -1, RETR and TOP return "-ERR
2158 * System error - couldn't open message", and
2159 * DELE succeeds but doesn't actually delete
2162 if (msgsizes && msgsizes[num-1] == -1)
2164 if (outlevel >= O_VERBOSE)
2166 "Skipping message %d, length -1",
2171 /* we may want to reject this message if it's old */
2174 if (outlevel > O_SILENT)
2176 error_build("skipping message %d", num);
2178 error_build(" (oversized, %d bytes)",
2184 flag wholesize = !protocol->fetch_body;
2186 /* request a message */
2187 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
2191 /* -1 means we didn't see a size in the response */
2192 if (len == -1 && msgsizes)
2194 len = msgsizes[num - 1];
2198 if (outlevel > O_SILENT)
2200 error_build("reading message %d of %d",
2204 error_build(" (%d %sbytes)",
2205 len, wholesize ? "" : "header ");
2206 if (outlevel == O_VERBOSE)
2207 error_complete(0, 0, "");
2212 /* later we'll test for this before closing */
2213 sinkfp = (FILE *)NULL;
2216 * Read the message headers and ship them to the
2219 ok = readheaders(sock, len, msgsizes[num-1],
2221 if (ok == PS_RETAINED)
2222 suppress_forward = retained = TRUE;
2223 else if (ok == PS_TRANSIENT)
2224 suppress_delete = suppress_forward = TRUE;
2225 else if (ok == PS_REFUSED)
2226 suppress_forward = TRUE;
2227 else if (ok == PS_TRUNCATED)
2228 suppress_readbody = TRUE;
2233 * If we're using IMAP4 or something else that
2234 * can fetch headers separately from bodies,
2235 * it's time to request the body now. This
2236 * fetch may be skipped if we got an anti-spam
2237 * or other PS_REFUSED error response during
2240 if (protocol->fetch_body && !suppress_readbody)
2242 if (outlevel == O_VERBOSE)
2243 fputc('\n', stderr);
2245 if ((ok = (protocol->trail)(sock, ctl, num)))
2248 if (!suppress_forward)
2250 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
2252 if (outlevel > O_SILENT && !wholesize)
2253 error_build(" (%d body bytes) ", len);
2257 /* process the body now */
2260 if (suppress_readbody)
2262 /* When readheaders returns PS_TRUNCATED,
2263 the body (which has no content
2264 has already been read by readheaders,
2265 so we say readbody returned PS_SUCCESS */
2275 if (ok == PS_TRANSIENT)
2276 suppress_delete = suppress_forward = TRUE;
2280 /* tell server we got it OK and resynchronize */
2281 if (protocol->trail)
2283 if (outlevel == O_VERBOSE)
2284 fputc('\n', stderr);
2286 ok = (protocol->trail)(sock, ctl, num);
2292 /* count # messages forwarded on this pass */
2293 if (!suppress_forward)
2297 * Check to see if the numbers matched?
2299 * Yes, some servers foo this up horribly.
2300 * All IMAP servers seem to get it right, and
2301 * so does Eudora QPOP at least in 2.xx
2304 * Microsoft Exchange gets it completely
2305 * wrong, reporting compressed rather than
2306 * actual sizes (so the actual length of
2307 * message is longer than the reported size).
2308 * Another fine example of Microsoft brain death!
2310 * Some older POP servers, like the old UCB
2311 * POP server and the pre-QPOP QUALCOMM
2312 * versions, report a longer size in the LIST
2313 * response than actually gets shipped up.
2314 * It's unclear what is going on here, as the
2315 * QUALCOMM server (at least) seems to be
2316 * reporting the on-disk size correctly.
2318 if (msgsizes && msglen != msgsizes[num-1])
2320 if (outlevel >= O_VERBOSE)
2322 "message %d was not the expected length (%d != %d)",
2323 num, msglen, msgsizes[num-1]);
2326 /* end-of-message processing starts here */
2332 /* close the delivery pipe, we'll reopen before next message */
2334 rc = pclose(sinkfp);
2337 signal(SIGCHLD, sigchld);
2340 error(0, -1, "MDA exited abnormally or returned nonzero status");
2344 else if (!suppress_forward)
2346 /* write message terminator */
2347 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2349 error(0, -1, "SMTP listener refused delivery");
2351 suppress_delete = TRUE;
2359 * At this point in flow of control, either
2360 * we've bombed on a protocol error or had
2361 * delivery refused by the SMTP server
2362 * (unlikely -- I've never seen it) or we've
2363 * seen `accepted for delivery' and the
2364 * message is shipped. It's safe to mark the
2365 * message seen and delete it on the server
2369 /* tell the UID code we've seen this */
2374 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2375 if (sdp->val.status.num == num)
2376 sdp->val.status.mark = UID_SEEN;
2379 /* maybe we delete this message now? */
2382 if (outlevel > O_SILENT)
2383 error_complete(0, 0, " retained");
2385 else if (protocol->delete
2387 && (fetch_it ? !ctl->keep : ctl->flush))
2390 if (outlevel > O_SILENT)
2391 error_complete(0, 0, " flushed");
2392 ok = (protocol->delete)(sock, ctl, num);
2396 delete_str(&ctl->newsaved, num);
2397 #endif /* POP3_ENABLE */
2399 else if (outlevel > O_SILENT)
2400 error_complete(0, 0, " not flushed");
2402 /* perhaps this as many as we're ready to handle */
2403 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2409 * Only re-poll if we had some actual forwards, allowed
2410 * deletions and had no errors.
2411 * Otherwise it is far too easy to get into infinite loops.
2413 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2417 ok = (protocol->logout_cmd)(sock, ctl);
2419 * Hmmmm...arguably this would be incorrect if we had fetches but
2420 * no dispatches (due to oversized messages, etc.)
2423 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2428 if (ok != 0 && ok != PS_SOCKET)
2429 (protocol->logout_cmd)(sock, ctl);
2433 msg = (char *)NULL; /* sacrifice to -Wall */
2440 msg = "authorization";
2443 msg = "missing or bad RFC822 header";
2449 msg = "client/server synchronization";
2452 msg = "client/server protocol";
2455 msg = "lock busy on server";
2458 msg = "SMTP transaction";
2464 error(0, 0, "undefined");
2467 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2468 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2469 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2470 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2473 /* execute post-initialization command, if any */
2474 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2478 sprintf(buf, "post-connection command failed with status %d", ok);
2480 if (ok == PS_SUCCESS)
2484 signal(SIGALRM, sigsave);
2488 #if defined(HAVE_STDARG_H)
2489 void gen_send(int sock, const char *fmt, ... )
2490 /* assemble command in printf(3) style and send to the server */
2492 void gen_send(sock, fmt, va_alist)
2493 /* assemble command in printf(3) style and send to the server */
2494 int sock; /* socket to which server is connected */
2495 const char *fmt; /* printf-style format */
2499 char buf [MSGBUFSIZE+1];
2502 if (protocol->tagged)
2503 (void) sprintf(buf, "%s ", GENSYM);
2507 #if defined(HAVE_STDARG_H)
2512 #ifdef HAVE_VSNPRINTF
2513 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2515 vsprintf(buf + strlen(buf), fmt, ap);
2519 strcat(buf, "\r\n");
2520 SockWrite(sock, buf, strlen(buf));
2522 if (outlevel == O_VERBOSE)
2526 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2530 sp = cp + strlen(shroud);
2536 buf[strlen(buf)-2] = '\0';
2537 error(0, 0, "%s> %s", protocol->name, buf);
2541 int gen_recv(sock, buf, size)
2542 /* get one line of input from the server */
2543 int sock; /* socket to which server is connected */
2544 char *buf; /* buffer to receive input */
2545 int size; /* length of buffer */
2547 int oldphase = phase; /* we don't have to be re-entrant */
2549 phase = SERVER_WAIT;
2550 set_timeout(mytimeout);
2551 if (SockRead(sock, buf, size) == -1)
2560 if (buf[strlen(buf)-1] == '\n')
2561 buf[strlen(buf)-1] = '\0';
2562 if (buf[strlen(buf)-1] == '\r')
2563 buf[strlen(buf)-1] = '\0';
2564 if (outlevel == O_VERBOSE)
2565 error(0, 0, "%s< %s", protocol->name, buf);
2571 #if defined(HAVE_STDARG_H)
2572 int gen_transact(int sock, char *fmt, ... )
2573 /* assemble command in printf(3) style, send to server, accept a response */
2575 int gen_transact(int sock, fmt, va_alist)
2576 /* assemble command in printf(3) style, send to server, accept a response */
2577 int sock; /* socket to which server is connected */
2578 const char *fmt; /* printf-style format */
2583 char buf [MSGBUFSIZE+1];
2585 int oldphase = phase; /* we don't have to be re-entrant */
2587 phase = SERVER_WAIT;
2589 if (protocol->tagged)
2590 (void) sprintf(buf, "%s ", GENSYM);
2594 #if defined(HAVE_STDARG_H)
2599 #ifdef HAVE_VSNPRINTF
2600 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2602 vsprintf(buf + strlen(buf), fmt, ap);
2606 strcat(buf, "\r\n");
2607 SockWrite(sock, buf, strlen(buf));
2609 if (outlevel == O_VERBOSE)
2613 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2617 sp = cp + strlen(shroud);
2623 buf[strlen(buf)-1] = '\0';
2624 error(0, 0, "%s> %s", protocol->name, buf);
2627 /* we presume this does its own response echoing */
2628 ok = (protocol->parse_response)(sock, buf);
2634 /* driver.c ends here */