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_RES_SEARCH
49 #endif /* HAVE_RES_SEARCH */
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 /* KERBEROS_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;
141 static void map_name(name, ctl, xmit_names)
142 /* add given name to xmit_names if it matches declared localnames */
143 const char *name; /* name to map */
144 struct query *ctl; /* list of permissible aliases */
145 struct idlist **xmit_names; /* list of recipient names parsed out */
151 lname = idpair_find(&ctl->localnames, name+off);
152 if (!lname && ctl->wildcard)
155 if (lname != (char *)NULL)
157 if (outlevel == O_VERBOSE)
158 error(0, 0, "mapped %s to local %s", name, lname);
159 save_str(xmit_names, lname, XMIT_ACCEPT);
164 void find_server_names(hdr, ctl, xmit_names)
165 /* parse names out of a RFC822 header into an ID list */
166 const char *hdr; /* RFC822 header in question */
167 struct query *ctl; /* list of permissible aliases */
168 struct idlist **xmit_names; /* list of recipient names parsed out */
170 if (hdr == (char *)NULL)
176 for (cp = nxtaddr(hdr);
183 * If the name of the user begins with a qmail virtual
184 * domain prefix, ignore the prefix. Doing this here
185 * means qvirtual will work either with ordinary name
186 * mapping or with a localdomains option.
188 if (ctl->server.qvirtual)
190 int sl = strlen(ctl->server.qvirtual);
192 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
196 if ((atsign = strchr(cp, '@'))) {
200 * Does a trailing segment of the hostname match something
201 * on the localdomains list? If so, save the whole name
204 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
207 rhs = atsign + (strlen(atsign) - strlen(idp->id));
209 (rhs[-1] == '.' || rhs[-1] == '@') &&
210 strcasecmp(rhs, idp->id) == 0)
212 if (outlevel == O_VERBOSE)
213 error(0, 0, "passed through %s matching %s",
215 save_str(xmit_names, cp, XMIT_ACCEPT);
221 /* if we matched a local domain, idp != NULL */
225 * Check to see if the right-hand part is an alias
226 * or MX equivalent of the mailserver. If it's
227 * not, skip this name. If it is, we'll keep
228 * going and try to find a mapping to a client name.
230 if (!is_host_alias(atsign+1, ctl))
232 save_str(xmit_names, cp, XMIT_REJECT);
238 map_name(cp, ctl, xmit_names);
245 static char *parse_received(struct query *ctl, char *bufp)
246 /* try to extract real address from the Received line */
247 /* If a valid Received: line is found, we return the full address in
248 * a buffer which can be parsed from nxtaddr(). This is to ansure that
249 * the local domain part of the address can be passed along in
250 * find_server_names() if it contains one.
251 * Note: We should return a dummy header containing the address
252 * which makes nxtaddr() behave correctly.
255 char *ok = (char *)NULL;
256 static char rbuf[HOSTLEN + USERNAMELEN + 4];
259 * Try to extract the real envelope addressee. We look here
260 * specifically for the mailserver's Received line.
261 * Note: this will only work for sendmail, or an MTA that
262 * shares sendmail's convention for embedding the envelope
263 * address in the Received line. Sendmail itself only
264 * does this when the mail has a single recipient.
266 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
270 /* extract space-delimited token after "by " */
271 for (sp = ok + 3; isspace(*sp); sp++)
274 for (; !isspace(*sp); sp++)
279 * If it's a DNS name of the mail server, look for the
280 * recipient name after a following "for". Otherwise
283 if (is_host_alias(rbuf, ctl) &&
284 (ok = strstr(sp, "for ")) &&
287 flag want_gt = FALSE;
291 *tp++ = ':'; /* Here is the hack. This is to be friends */
292 *tp++ = ' '; /* with nxtaddr()... */
298 while (*sp == '@') /* skip routes */
299 while (*sp && *sp++ != ':')
302 && (want_gt ? (*sp != '>') : !isspace(*sp))
308 /* uh oh -- whitespace here can't be right! */
314 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
324 if (outlevel == O_VERBOSE) {
325 char *lf = rbuf + strlen(rbuf)-1;
327 error(0, 0, "found Received address `%s'", rbuf+2);
334 static int smtp_open(struct query *ctl)
335 /* try to open a socket to the appropriate SMTP server for this query */
337 /* maybe it's time to close the socket in order to force delivery */
338 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
340 close(ctl->smtp_socket);
341 ctl->smtp_socket = -1;
345 /* if no socket to any SMTP host is already set up, try to open one */
346 if (ctl->smtp_socket == -1)
349 * RFC 1123 requires that the domain name in HELO address is a
350 * "valid principal domain name" for the client host. If we're
351 * running in invisible mode, violate this with malice
352 * aforethought in order to make the Received headers and
353 * logging look right.
355 * In fact this code relies on the RFC1123 requirement that the
356 * SMTP listener must accept messages even if verification of the
357 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
359 * How we compute the true mailhost name to pass to the
360 * listener doesn't affect behavior on RFC1123- violating
361 * listeners that check for name match; we're going to lose
362 * on those anyway because we can never give them a name
363 * that matches the local machine fetchmail is running on.
364 * What it will affect is the listener's logging.
367 char *id_me = run.invisible ? ctl->server.truename : "localhost";
368 int oldphase = phase;
373 * Run down the SMTP hunt list looking for a server that's up.
374 * Use both explicit hunt entries (value TRUE) and implicit
375 * (default) ones (value FALSE).
378 phase = LISTENER_WAIT;
380 set_timeout(ctl->server.timeout);
381 for (idp = ctl->smtphunt; idp; idp = idp->next)
383 char *cp, *parsed_host = alloca(strlen(idp->id) + 1);
385 char *portnum = SMTP_PORT;
387 int portnum = SMTP_PORT;
390 ctl->smtphost = idp->id; /* remember last host tried. */
392 strcpy(parsed_host, idp->id);
393 if ((cp = strrchr(parsed_host, '/')))
403 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
406 /* first, probe for ESMTP */
407 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
408 SMTP_ehlo(ctl->smtp_socket, id_me,
409 &ctl->server.esmtp_options) == SM_OK)
413 * RFC 1869 warns that some listeners hang up on a failed EHLO,
414 * so it's safest not to assume the socket will still be good.
416 SockClose(ctl->smtp_socket);
417 ctl->smtp_socket = -1;
419 /* if opening for ESMTP failed, try SMTP */
420 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
423 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
424 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
427 SockClose(ctl->smtp_socket);
428 ctl->smtp_socket = -1;
434 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
435 error(0, 0, "forwarding to %s", ctl->smtphost);
437 return(ctl->smtp_socket);
440 /* these are shared by stuffline, readheaders and readbody */
442 static RETSIGTYPE (*sigchld)();
443 static int sizeticker;
445 static int stuffline(struct query *ctl, char *buf)
446 /* ship a line to the given control block's output sink (SMTP server or MDA) */
451 /* The line may contain NUL characters. Find the last char to use
452 * -- the real line termination is the sequence "\n\0".
455 while ((last += strlen(last)) && (last[-1] != '\n'))
458 /* fix message lines that have only \n termination (for qmail) */
461 if (last - 1 == buf || last[-2] != '\r')
470 phase = FORWARDING_WAIT;
473 * SMTP byte-stuffing. We only do this if the protocol does *not*
474 * use .<CR><LF> as EOM. If it does, the server will already have
475 * decorated any . lines it sends back up.
478 if (protocol->delimited) /* server has already byte-stuffed */
483 /* writing to SMTP, leave the byte-stuffing in place */;
485 else /* if (!protocol->delimited) -- not byte-stuffed already */
488 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
490 /* leave it alone */;
493 /* we may need to strip carriage returns */
498 for (sp = tp = buf; sp < last; sp++)
507 n = fwrite(buf, 1, last - buf, sinkfp);
508 else if (ctl->smtp_socket != -1)
509 n = SockWrite(ctl->smtp_socket, buf, last - buf);
517 static void sanitize(s)
518 /* replace unsafe shellchars by an _ */
521 static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
524 for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
529 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
531 static int readheaders(sock, fetchlen, reallen, ctl, num)
532 /* read message headers and ship to SMTP or MDA */
533 int sock; /* to which the server is connected */
534 long fetchlen; /* length of message according to fetch response */
535 long reallen; /* length of message according to getsizes */
536 struct query *ctl; /* query control record */
537 int num; /* index of message */
542 struct addrblk *next;
544 struct addrblk *to_addrchain = NULL;
545 struct addrblk **to_chainptr = &to_addrchain;
546 struct addrblk *resent_to_addrchain = NULL;
547 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
549 char buf[MSGBUFSIZE+1];
550 char return_path[HOSTLEN + USERNAMELEN + 4];
551 int from_offs, reply_to_offs, resent_from_offs;
552 int app_from_offs, sender_offs, resent_sender_offs;
554 char *headers, *received_for, *destaddr, *rcv, *cp;
555 int n, linelen, oldlen, ch, remaining, skipcount;
556 struct idlist *idp, *xmit_names;
557 flag good_addresses, bad_addresses, has_nuls;
558 flag no_local_matches = FALSE;
563 has_nuls = headers_ok = FALSE;
564 return_path[0] = '\0';
565 olderrs = ctl->errcount;
567 /* read message headers */
568 headers = received_for = NULL;
569 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
570 sender_offs = resent_sender_offs = env_offs = -1;
576 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
580 line = xmalloc(sizeof(buf));
584 set_timeout(ctl->server.timeout);
585 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
595 /* lines may not be properly CRLF terminated; fix this for qmail */
598 cp = buf + strlen(buf) - 1;
599 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
608 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
612 /* check for end of headers */
616 has_nuls = (linelen != strlen(line));
618 goto process_headers;
622 * Check for end of message immediately. If one of your folders
623 * has been mangled, the delimiter may occur directly after the
626 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
629 has_nuls = (linelen != strlen(line));
630 goto process_headers;
633 /* we may need to grab RFC822 continuations */
634 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
636 /* write the message size dots */
637 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
639 sizeticker += linelen;
640 while (sizeticker >= SIZETICKER)
643 sizeticker -= SIZETICKER;
647 /* we see an ordinary (non-header, non-message-delimiter line */
648 has_nuls = (linelen != strlen(line));
651 * The University of Washington IMAP server (the reference
652 * implementation of IMAP4 written by Mark Crispin) relies
653 * on being able to keep base-UID information in a special
654 * message at the head of the mailbox. This message should
655 * neither be deleted nor forwarded.
659 * We disable this check under POP2 because there's no way to
660 * prevent deletion of the message. So at least we ought to
661 * forward it to the user so he or she will have some clue
662 * that things have gone awry.
664 if (protocol->port != 109)
665 #endif /* POP2_ENABLE */
666 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
673 * This code prevents fetchmail from becoming an accessory after
674 * the fact to upstream sendmails with the `E' option on. It also
675 * copes with certain brain-dead POP servers (like NT's) that pass
676 * through Unix from_ lines.
678 * Either of these bugs can result in a non-RFC822 line at the
679 * beginning of the headers. If fetchmail just passes it
680 * through, the client listener may think the message has *no*
681 * headers (since the first) line it sees doesn't look
682 * RFC822-conformant) and fake up a set.
684 * What the user would see in this case is bogus (synthesized)
685 * headers, followed by a blank line, followed by the >From,
686 * followed by the real headers, followed by a blank line,
689 * We forestall this lossage by tossing anything that looks
690 * like an escaped or passed-through From_ line in headers.
691 * These aren't RFC822 so our conscience is clear...
693 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
700 * If we see a Status line, it may have been inserted by an MUA
701 * on the mail host, or it may have been inserted by the server
702 * program after the headers in the transaction stream. This
703 * can actually hose some new-mail notifiers such as xbuffy,
704 * which assumes any Status line came from a *local* MDA and
705 * therefore indicates that the message has been seen.
707 * Some buggy POP servers (including at least the 3.3(20)
708 * version of the one distributed with IMAP) insert empty
709 * Status lines in the transaction stream; we'll chuck those
710 * unconditionally. Nonempty ones get chucked if the user
711 * turns on the dropstatus flag.
716 if (!strncasecmp(line, "Status:", 7))
718 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
723 while (*cp && isspace(*cp)) cp++;
724 if (!*cp || ctl->dropstatus)
733 line = reply_hack(line, ctl->server.truename);
736 * OK, this is messy. If we're forwarding by SMTP, it's the
737 * SMTP-receiver's job (according to RFC821, page 22, section
738 * 4.1.1) to generate a Return-Path line on final delivery.
739 * The trouble is, we've already got one because the
740 * mailserver's SMTP thought *it* was responsible for final
743 * Stash away the contents of Return-Path for use in generating
744 * MAIL FROM later on, then prevent the header from being saved
745 * with the others. In effect, we strip it off here.
747 * If the SMTP server conforms to the standards, and fetchmail gets the
748 * envelope sender from the Return-Path, the new Return-Path should be
749 * exactly the same as the original one.
751 * We do *not* want to ignore empty Return-Path headers. These should
752 * be passed through as a way of indicating that a message should
753 * not trigger bounces if delivery fails. What we *do* need to do is
754 * make sure we never try to rewrite such a blank Return-Path. We
755 * handle this with a check for <> in the rewrite logic.
757 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
759 strcpy(return_path, cp);
768 oldlen = strlen(line);
769 headers = xmalloc(oldlen + 1);
770 (void) strcpy(headers, line);
778 newlen = oldlen + strlen(line);
779 headers = (char *) realloc(headers, newlen + 1);
780 if (headers == NULL) {
784 strcpy(headers + oldlen, line);
786 line = headers + oldlen;
790 if (!strncasecmp("From:", line, 5))
791 from_offs = (line - headers);
792 else if (!strncasecmp("Reply-To:", line, 9))
793 reply_to_offs = (line - headers);
794 else if (!strncasecmp("Resent-From:", line, 12))
795 resent_from_offs = (line - headers);
796 else if (!strncasecmp("Apparently-From:", line, 16))
797 app_from_offs = (line - headers);
798 else if (!strncasecmp("Sender:", line, 7))
799 sender_offs = (line - headers);
800 else if (!strncasecmp("Resent_Sender:", line, 14))
801 resent_sender_offs = (line - headers);
803 else if (!strncasecmp("Message-Id:", buf, 11))
805 if (ctl->server.uidl)
809 buf[IDLEN+12] = 0; /* prevent stack overflow */
810 sscanf(buf+12, "%s", id);
811 if (!str_find( &ctl->newsaved, num))
813 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
814 new->val.status.num = num;
819 else if (!MULTIDROP(ctl))
822 else if (!strncasecmp("To:", line, 3)
823 || !strncasecmp("Cc:", line, 3)
824 || !strncasecmp("Bcc:", line, 4)
825 || !strncasecmp("Apparently-To:", line, 14))
827 *to_chainptr = xmalloc(sizeof(struct addrblk));
828 (*to_chainptr)->offset = (line - headers);
829 to_chainptr = &(*to_chainptr)->next;
833 else if (!strncasecmp("Resent-To:", line, 10)
834 || !strncasecmp("Resent-Cc:", line, 10)
835 || !strncasecmp("Resent-Bcc:", line, 11))
837 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
838 (*resent_to_chainptr)->offset = (line - headers);
839 resent_to_chainptr = &(*resent_to_chainptr)->next;
840 *resent_to_chainptr = NULL;
843 else if (ctl->server.envelope != STRING_DISABLED)
845 if (ctl->server.envelope
846 && strcasecmp(ctl->server.envelope, "Received"))
848 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
850 strlen(ctl->server.envelope)))
852 if (skipcount++ != ctl->server.envskip)
854 env_offs = (line - headers);
857 else if (!received_for && !strncasecmp("Received:", line, 9))
859 if (skipcount++ != ctl->server.envskip)
861 received_for = parse_received(ctl, line);
868 * We want to detect this early in case there are so few headers that the
869 * dispatch logic barfs.
873 if (outlevel > O_SILENT)
874 error(0,0,"message delimiter found while scanning headers");
878 * Hack time. If the first line of the message was blank, with no headers
879 * (this happens occasionally due to bad gatewaying software) cons up
880 * a set of fake headers.
882 * If you modify the fake header template below, be sure you don't
883 * make either From or To address @-less, otherwise the reply_hack
884 * logic will do bad things.
886 if (headers == (char *)NULL)
889 snprintf(buf, sizeof(buf),
892 #endif /* HAVE_SNPRINTF */
893 "From: FETCHMAIL-DAEMON\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
894 user, ctl->remotename, ctl->server.truename);
895 headers = xstrdup(buf);
899 * We can now process message headers before reading the text.
900 * In fact we have to, as this will tell us where to forward to.
903 /* Decode MIME encoded headers. We MUST do this before
904 * looking at the Content-Type / Content-Transfer-Encoding
905 * headers (RFC 2046).
907 if (ctl->mimedecode) {
908 UnMimeHeader(headers);
910 /* Check for MIME headers indicating possible 8-bit data */
911 mimemsg = MimeBodyType(headers, ctl->mimedecode);
914 * If there is a Return-Path address on the message, this was
915 * almost certainly the MAIL FROM address given the originating
916 * sendmail. This is the best thing to use for logging the
917 * message origin (it sets up the right behavior for bounces and
918 * mailing lists). Otherwise, fall down to the next available
919 * envelope address (which is the most probable real sender).
920 * *** The order is important! ***
921 * This is especially useful when receiving mailing list
922 * messages in multidrop mode. if a local address doesn't
923 * exist, the bounce message won't be returned blindly to the
924 * author or to the list itself but rather to the list manager
925 * (ex: specified by "Sender:") wich is less anoying. This is
926 * true for most mailing list packages.
928 if( !return_path[0] ){
930 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
931 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
932 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
933 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
934 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
935 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
936 if (ap) strcpy( return_path, ap );
939 /* cons up a list of local recipients */
940 xmit_names = (struct idlist *)NULL;
941 bad_addresses = good_addresses = accept_count = reject_count = 0;
942 /* is this a multidrop box? */
945 if (env_offs > -1) /* We have the actual envelope addressee */
946 find_server_names(headers + env_offs, ctl, &xmit_names);
947 else if (received_for)
949 * We have the Received for addressee.
950 * It has to be a mailserver address, or we
951 * wouldn't have got here.
952 * We use find_server_names() to let local
953 * hostnames go through.
955 find_server_names(received_for, ctl, &xmit_names);
959 find_server_names(sdps_envto, ctl, &xmit_names);
962 #endif /* SDPS_ENABLE */
966 * We haven't extracted the envelope address.
967 * So check all the "Resent-To" header addresses if
968 * they exist. If and only if they don't, consider
971 register struct addrblk *nextptr;
972 if (resent_to_addrchain) {
973 /* delete the "To" chain and substitute it
974 * with the "Resent-To" list
976 while (to_addrchain) {
977 nextptr = to_addrchain->next;
979 to_addrchain = nextptr;
981 to_addrchain = resent_to_addrchain;
982 resent_to_addrchain = NULL;
984 /* now look for remaining adresses */
985 while (to_addrchain) {
986 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
987 nextptr = to_addrchain->next;
989 to_addrchain = nextptr;
994 no_local_matches = TRUE;
995 save_str(&xmit_names, run.postmaster, XMIT_ACCEPT);
996 if (outlevel == O_VERBOSE)
998 "no local matches, forwarding to %s",
1002 else /* it's a single-drop box, use first localname */
1003 save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
1007 * Time to either address the message or decide we can't deliver it yet.
1009 if (ctl->errcount > olderrs) /* there were DNS errors above */
1011 if (outlevel == O_VERBOSE)
1012 error(0,0, "forwarding and deletion suppressed due to DNS errors");
1014 free_str_list(&xmit_names);
1015 return(PS_TRANSIENT);
1017 else if (ctl->mda) /* we have a declared MDA */
1019 int length = 0, fromlen = 0, nameslen = 0;
1020 char *names = NULL, *before, *after, *from = NULL;
1022 for (idp = xmit_names; idp; idp = idp->next)
1023 if (idp->val.status.mark == XMIT_ACCEPT)
1026 destaddr = "localhost";
1028 length = strlen(ctl->mda);
1029 before = xstrdup(ctl->mda);
1031 /* get user addresses for %T (or %s for backward compatibility) */
1032 if (strstr(before, "%s") || strstr(before, "%T"))
1035 * We go through this in order to be able to handle very
1036 * long lists of users and (re)implement %s.
1039 for (idp = xmit_names; idp; idp = idp->next)
1040 if (idp->val.status.mark == XMIT_ACCEPT)
1041 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1043 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1045 for (idp = xmit_names; idp; idp = idp->next)
1046 if (idp->val.status.mark == XMIT_ACCEPT)
1048 strcat(names, idp->id);
1051 names[--nameslen] = '\0'; /* chop trailing space */
1053 /* sanitize names in order to contain *only* harmless shell chars */
1057 /* get From address for %F */
1058 if (strstr(before, "%F"))
1060 from = xstrdup(return_path);
1062 /* sanitize from in order to contain *only* harmless shell chars */
1065 fromlen = strlen(from);
1068 /* do we have to build an mda string? */
1069 if (names || from) {
1074 /* find length of resulting mda string */
1076 while (sp = strstr(sp, "%s")) {
1077 length += nameslen - 2; /* subtract %s */
1081 while (sp = strstr(sp, "%T")) {
1082 length += nameslen - 2; /* subtract %T */
1086 while (sp = strstr(sp, "%F")) {
1087 length += fromlen - 2; /* subtract %F */
1091 after = xmalloc(length + 1);
1093 /* copy mda source string to after, while expanding %[sTF] */
1094 for (dp = after, sp = before; *dp = *sp; dp++, sp++) {
1095 if (sp[0] != '%') continue;
1097 /* need to expand? BTW, no here overflow, because in
1098 ** the worst case (end of string) sp[1] == '\0' */
1099 if (sp[1] == 's' || sp[1] == 'T') {
1102 sp++; /* position sp over [sT] */
1103 dp--; /* adjust dp */
1104 } else if (sp[1] == 'F') {
1107 sp++; /* position sp over F */
1108 dp--; /* adjust dp */
1127 if (outlevel == O_VERBOSE)
1128 error(0, 0, "about to deliver with: %s", before);
1132 * Arrange to run with user's permissions if we're root.
1133 * This will initialize the ownership of any files the
1134 * MDA creates properly. (The seteuid call is available
1135 * under all BSDs and Linux)
1138 #endif /* HAVE_SETEUID */
1140 sinkfp = popen(before, "w");
1145 /* this will fail quietly if we didn't start as root */
1147 #endif /* HAVE_SETEUID */
1151 error(0, 0, "MDA open failed");
1153 free_str_list(&xmit_names);
1157 sigchld = signal(SIGCHLD, SIG_DFL);
1161 char *ap, options[MSGBUFSIZE], addr[128];
1163 /* build a connection to the SMTP listener */
1164 if ((smtp_open(ctl) == -1))
1166 error(0, errno, "SMTP connect to %s failed",
1167 ctl->smtphost ? ctl->smtphost : "localhost");
1169 free_str_list(&xmit_names);
1174 * Compute ESMTP options.
1177 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
1178 if (ctl->pass8bits || (mimemsg & MSG_IS_8BIT))
1179 strcpy(options, " BODY=8BITMIME");
1180 else if (mimemsg & MSG_IS_7BIT)
1181 strcpy(options, " BODY=7BIT");
1184 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1185 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1188 * Try to get the SMTP listener to take the Return-Path
1189 * address as MAIL FROM . If it won't, fall back on the
1190 * calling-user ID. This won't affect replies, which use the
1191 * header From address anyway.
1193 * RFC 1123 requires that the domain name part of the
1194 * MAIL FROM address be "canonicalized", that is a
1195 * FQDN or MX but not a CNAME. We'll assume the From
1196 * header is already in this form here (it certainly
1197 * is if rewrite is on). RFC 1123 is silent on whether
1198 * a nonexistent hostname part is considered canonical.
1200 * This is a potential problem if the MTAs further upstream
1201 * didn't pass canonicalized From/Return-Path lines, *and* the
1202 * local SMTP listener insists on them.
1204 * None of these error conditions generates bouncemail. Comments
1205 * below explain for each case why this is so.
1207 ap = (return_path[0]) ? return_path : user;
1208 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1210 int smtperr = atoi(smtp_response);
1212 if (str_find(&ctl->antispam, smtperr))
1215 * SMTP listener explicitly refuses to deliver mail
1216 * coming from this address, probably due to an
1217 * anti-spam domain exclusion. Respect this. Don't
1218 * try to ship the message, and don't prevent it from
1219 * being deleted. Typical values:
1221 * 501 = exim's old antispam response
1222 * 550 = exim's new antispam response (temporary)
1223 * 553 = sendmail 8.8.7's generic REJECT
1224 * 571 = sendmail's "unsolicited email refused"
1226 * We don't send bouncemail on antispam failures because
1227 * we don't want the scumbags to know the address is even
1230 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1232 free_str_list(&xmit_names);
1237 * Suppress error message only if the response specifically
1238 * meant `excluded for policy reasons'. We *should* see
1239 * an error when the return code is less specific.
1242 error(0, -1, "SMTP error: %s", smtp_response);
1246 case 452: /* insufficient system storage */
1248 * Temporary out-of-queue-space condition on the
1249 * ESMTP server. Don't try to ship the message,
1250 * and suppress deletion so it can be retried on
1251 * a future retrieval cycle.
1253 * Bouncemail *might* be appropriate here as a delay
1254 * notification. But it's not really necessary because
1255 * this is not an actual failure, we're very likely to be
1256 * able to recover on the next cycle.
1258 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1260 free_str_list(&xmit_names);
1261 return(PS_TRANSIENT);
1263 case 552: /* message exceeds fixed maximum message size */
1264 case 553: /* invalid sending domain */
1266 * Permanent no-go condition on the
1267 * ESMTP server. Don't try to ship the message,
1268 * and allow it to be deleted.
1270 * Bouncemail would be appropriate for 552, but in these
1271 * latter days 553 usually means a spammer is trying to
1272 * cover his tracks. We'd rather deny the scumbags any
1273 * feedback that the address is valid.
1275 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1277 free_str_list(&xmit_names);
1280 default: /* retry with invoking user's address */
1281 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1283 error(0, -1, "SMTP error: %s", smtp_response);
1285 free_str_list(&xmit_names);
1286 return(PS_SMTP); /* should never happen */
1292 * Now list the recipient addressees
1294 * RFC 1123 requires that the domain name part of the
1295 * RCPT TO address be "canonicalized", that is a FQDN
1296 * or MX but not a CNAME. Some listeners (like exim)
1299 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1301 for (idp = xmit_names; idp; idp = idp->next)
1302 if (idp->val.status.mark == XMIT_ACCEPT)
1304 if (strchr(idp->id, '@'))
1305 strcpy(addr, idp->id);
1307 #ifdef HAVE_SNPRINTF
1308 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1310 sprintf(addr, "%s@%s", idp->id, destaddr);
1311 #endif /* HAVE_SNPRINTF */
1313 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1318 idp->val.status.mark = XMIT_ANTISPAM;
1320 "SMTP listener doesn't like recipient address `%s'",
1324 if (!good_addresses)
1326 #ifdef HAVE_SNPRINTF
1327 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1329 sprintf(addr, "%s@%s", user, destaddr);
1330 #endif /* HAVE_SNPRINTF */
1332 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1334 error(0, 0, "can't even send to calling user!");
1336 free_str_list(&xmit_names);
1341 /* tell it we're ready to send data */
1342 SMTP_data(ctl->smtp_socket);
1347 * Some server/sendmail combinations cause problems when our
1348 * synthetic Received line is before the From header. Cope
1351 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1356 n = stuffline(ctl, headers);
1359 if (!run.invisible && n != -1)
1361 /* utter any per-message Received information we need here */
1362 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1363 n = stuffline(ctl, buf);
1367 * We used to include ctl->remotename in this log line,
1368 * but this can be secure information that would be bad
1371 sprintf(buf, "\tby fetchmail-%s %s\n",
1374 n = stuffline(ctl, buf);
1380 if (good_addresses == 0)
1383 "for <%s@%s> (by default); ",
1386 else if (good_addresses == 1)
1388 for (idp = xmit_names; idp; idp = idp->next)
1389 if (idp->val.status.mark == XMIT_ACCEPT)
1390 break; /* only report first address */
1391 if (strchr(idp->id, '@'))
1392 sprintf(buf+1, "for <%s>", idp->id);
1394 sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1395 sprintf(buf+strlen(buf), " (%s); ",
1396 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1402 #ifdef HAVE_STRFTIME
1404 * Conform to RFC822. This is typically going to emit
1405 * a three-letter timezone for %Z, which is going to
1406 * be marked "obsolete syntax" in 822bis. Note that we
1407 * generate a 4-digit year here.
1409 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1410 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1413 * This is really just a portability fallback, as the
1414 * date format ctime(3) emits is not RFC822
1417 strcat(buf, ctime(&now));
1418 #endif /* HAVE_STRFTIME */
1419 n = stuffline(ctl, buf);
1425 n = stuffline(ctl, rcv); /* ship out rest of headers */
1429 error(0, errno, "writing RFC822 headers");
1434 signal(SIGCHLD, sigchld);
1437 free_str_list(&xmit_names);
1440 else if (!run.use_syslog && outlevel == O_VERBOSE)
1443 /* write error notifications */
1444 if (no_local_matches || has_nuls || bad_addresses)
1447 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1450 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1451 if (no_local_matches)
1453 if (reject_count != 1)
1454 strcat(errhd, "no recipient addresses matched declared local names");
1457 for (idp = xmit_names; idp; idp = idp->next)
1458 if (idp->val.status.mark == XMIT_REJECT)
1460 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1466 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1467 strcat(errhd, "; ");
1468 strcat(errhd, "message has embedded NULs");
1473 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1474 strcat(errhd, "; ");
1475 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1476 errlen = strlen(errhd);
1477 for (idp = xmit_names; idp; idp = idp->next)
1478 if (idp->val.status.mark == XMIT_ANTISPAM)
1479 errlen += strlen(idp->id) + 2;
1481 errmsg = alloca(errlen+3);
1482 (void) strcpy(errmsg, errhd);
1483 for (idp = xmit_names; idp; idp = idp->next)
1484 if (idp->val.status.mark == XMIT_ANTISPAM)
1486 strcat(errmsg, idp->id);
1488 strcat(errmsg, ", ");
1493 strcat(errmsg, "\n");
1495 /* ship out the error line */
1497 stuffline(ctl, errmsg);
1500 /* issue the delimiter line */
1505 stuffline(ctl, buf);
1508 free_str_list(&xmit_names);
1509 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1512 static int readbody(sock, ctl, forward, len)
1513 /* read and dispose of a message body presented on sock */
1514 struct query *ctl; /* query control record */
1515 int sock; /* to which the server is connected */
1516 int len; /* length of message */
1517 flag forward; /* TRUE to forward */
1520 unsigned char buf[MSGBUFSIZE+4];
1521 unsigned char *inbufp = buf;
1522 flag issoftline = FALSE;
1524 /* pass through the text lines */
1525 while (protocol->delimited || len > 0)
1527 set_timeout(ctl->server.timeout);
1528 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1535 signal(SIGCHLD, sigchld);
1541 /* write the message size dots */
1544 sizeticker += linelen;
1545 while (sizeticker >= SIZETICKER)
1547 if (!run.use_syslog && outlevel > O_SILENT)
1549 sizeticker -= SIZETICKER;
1554 /* check for end of message */
1555 if (protocol->delimited && *inbufp == '.')
1556 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1558 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1561 msglen--; /* subtract the size of the dot escape */
1565 if (ctl->mimedecode && (mimemsg & MSG_NEEDS_DECODE)) {
1566 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1567 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1570 * Soft linebreak, but less than 200 bytes left in
1571 * input buffer. Rather than doing a buffer overrun,
1572 * ignore the soft linebreak, NL-terminate data and
1573 * deliver what we have now.
1574 * (Who writes lines longer than 2K anyway?)
1576 *inbufp = '\n'; *(inbufp+1) = '\0';
1581 /* ship out the text line */
1582 if (forward && (!issoftline))
1587 /* guard against very long lines */
1588 buf[MSGBUFSIZE+1] = '\r';
1589 buf[MSGBUFSIZE+2] = '\n';
1590 buf[MSGBUFSIZE+3] = '\0';
1592 n = stuffline(ctl, buf);
1596 error(0, errno, "writing message text");
1601 signal(SIGCHLD, sigchld);
1605 else if (outlevel == O_VERBOSE)
1615 kerberos_auth (socket, canonical)
1616 /* authenticate to the server host using Kerberos V4 */
1617 int socket; /* socket to server host */
1619 char *canonical; /* server name */
1621 const char *canonical; /* server name */
1624 char * host_primary;
1628 Key_schedule schedule;
1631 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1632 rem = (krb_sendauth (0L, socket, ticket, "pop",
1634 ((char *) (krb_realmofhost (canonical))),
1635 ((unsigned long) 0),
1639 ((struct sockaddr_in *) 0),
1640 ((struct sockaddr_in *) 0),
1643 if (rem != KSUCCESS)
1645 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1646 return (PS_AUTHFAIL);
1650 #endif /* KERBEROS_V4 */
1654 kerberos5_auth(socket, canonical)
1655 /* authernticate to the server host using Kerberos V5 */
1656 int socket; /* socket to server host */
1657 const char *canonical; /* server name */
1659 krb5_error_code retval;
1660 krb5_context context;
1662 krb5_principal client = NULL, server = NULL;
1663 krb5_error *err_ret = NULL;
1665 krb5_auth_context auth_context = NULL;
1667 krb5_init_context(&context);
1668 krb5_init_ets(context);
1669 krb5_auth_con_init(context, &auth_context);
1671 if (retval = krb5_cc_default(context, &ccdef)) {
1672 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1676 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1677 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1681 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1684 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1688 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1689 "KPOPV1.0", client, server,
1690 AP_OPTS_MUTUAL_REQUIRED,
1691 NULL, /* no data to checksum */
1692 0, /* no creds, use ccache instead */
1696 NULL); /* don't need reply */
1698 krb5_free_principal(context, server);
1699 krb5_free_principal(context, client);
1700 krb5_auth_con_free(context, auth_context);
1703 if (err_ret && err_ret->text.length) {
1704 error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1705 error_message(retval),
1706 err_ret->text.length,
1707 err_ret->text.data);
1708 krb5_free_error(context, err_ret);
1710 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1716 #endif /* KERBEROS_V5 */
1718 int do_protocol(ctl, proto)
1719 /* retrieve messages from server using given protocol method table */
1720 struct query *ctl; /* parsed options with merged-in defaults */
1721 const struct method *proto; /* protocol method table */
1723 int ok, js, sock = -1;
1728 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1730 error(0, -1, "Kerberos V4 support not linked.");
1733 #endif /* KERBEROS_V4 */
1736 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1738 error(0, -1, "Kerberos V5 support not linked.");
1741 #endif /* KERBEROS_V5 */
1743 /* lacking methods, there are some options that may fail */
1746 /* check for unsupported options */
1749 "Option --flush is not supported with %s",
1753 else if (ctl->fetchall) {
1755 "Option --all is not supported with %s",
1760 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1763 "Option --limit is not supported with %s",
1771 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1774 /* set up the server-nonresponse timeout */
1775 sigsave = signal(SIGALRM, timeout_handler);
1776 mytimeout = ctl->server.timeout;
1778 if ((js = setjmp(restart)) == 1)
1780 if (phase == SERVER_WAIT)
1782 "timeout after %d seconds waiting for server %s.",
1783 ctl->server.timeout, ctl->server.pollname);
1784 else if (phase == FORWARDING_WAIT)
1786 "timeout after %d seconds waiting for %s.",
1787 ctl->server.timeout,
1788 ctl->mda ? "MDA" : "SMTP");
1789 else if (phase == LISTENER_WAIT)
1791 "timeout after %d seconds waiting for listener to respond.");
1793 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1795 if (ctl->smtp_socket != -1)
1796 close(ctl->smtp_socket);
1805 char buf [POPBUFSIZE+1], *realhost;
1806 int *msgsizes, len, num, count, new, bytes, deletions = 0;
1808 int fetches, dispatches;
1810 int port, fetches, dispatches;
1814 /* execute pre-initialization command, if any */
1815 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1817 sprintf(buf, "pre-connection command failed with status %d", ok);
1823 /* open a socket to the mail server */
1825 port = ctl->server.port ? ctl->server.port : protocol->port;
1827 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1829 if ((sock = SockOpen(realhost,
1830 ctl->server.service ? ctl->server.service : protocol->service,
1831 ctl->server.netsec)) == -1)
1833 if ((sock = SockOpen(realhost, port, NULL)) == -1)
1837 #ifndef EHOSTUNREACH
1838 #define EHOSTUNREACH (-1)
1840 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1842 error_build("fetchmail: %s connection to %s failed: ",
1843 protocol->name, ctl->server.pollname);
1844 #ifdef HAVE_RES_SEARCH
1845 if (h_errno == HOST_NOT_FOUND)
1846 error_complete(0, 0, "host is unknown");
1847 else if (h_errno == NO_ADDRESS)
1848 error_complete(0, 0, "name is valid but has no IP address");
1849 else if (h_errno == NO_RECOVERY)
1850 error_complete(0, 0, "unrecoverable name server error");
1851 else if (h_errno == TRY_AGAIN)
1852 error_complete(0, 0, "temporary name server error");
1854 error_complete(0, 0, "unknown DNS error %d", h_errno);
1856 #endif /* HAVE_RES_SEARCH */
1857 error_complete(0, errno, "local error");
1865 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1867 set_timeout(ctl->server.timeout);
1868 ok = kerberos_auth(sock, ctl->server.truename);
1873 #endif /* KERBEROS_V4 */
1876 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1878 set_timeout(ctl->server.timeout);
1879 ok = kerberos5_auth(sock, ctl->server.truename);
1884 #endif /* KERBEROS_V5 */
1886 /* accept greeting message from mail server */
1887 ok = (protocol->parse_response)(sock, buf);
1891 /* try to get authorized to fetch mail */
1892 if (protocol->getauth)
1894 if (protocol->password_canonify)
1895 (protocol->password_canonify)(shroud, ctl->password);
1897 strcpy(shroud, ctl->password);
1899 ok = (protocol->getauth)(sock, ctl, buf);
1902 if (ok == PS_LOCKBUSY)
1903 error(0, -1, "Lock-busy error on %s@%s",
1905 ctl->server.truename);
1910 error(0, -1, "Authorization failure on %s@%s",
1912 ctl->server.truename);
1918 ctl->errcount = fetches = 0;
1920 /* now iterate over each folder selected */
1921 for (idp = ctl->mailboxes; idp; idp = idp->next)
1928 if (outlevel >= O_VERBOSE)
1930 error(0, 0, "selecting or re-polling folder %s", idp->id);
1932 error(0, 0, "selecting or re-polling default folder");
1934 /* compute # of messages and number of new messages waiting */
1935 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1940 * We need the size of each message before it's
1941 * loaded in order to pass via the ESMTP SIZE
1942 * option. If the protocol has a getsizes method,
1943 * we presume this means it doesn't get reliable
1944 * sizes from message fetch responses.
1946 if (count > 0 && proto->getsizes)
1950 msgsizes = (int *)alloca(sizeof(int) * count);
1951 for (i = 0; i < count; i++)
1954 ok = (proto->getsizes)(sock, count, msgsizes);
1961 for (i = 0; i < count; i++)
1962 bytes += msgsizes[i];
1966 /* show user how many messages we downloaded */
1968 (void) sprintf(buf, "%s at %s (folder %s)",
1969 ctl->remotename, ctl->server.truename, idp->id);
1971 (void) sprintf(buf, "%s at %s",
1972 ctl->remotename, ctl->server.truename);
1973 if (outlevel > O_SILENT)
1974 if (count == -1) /* only used for ETRN */
1975 error(0, 0, "Polling %s", ctl->server.truename);
1976 else if (count != 0)
1978 if (new != -1 && (count - new) > 0)
1979 error_build("%d message%s (%d seen) for %s",
1980 count, count > 1 ? "s" : "", count-new, buf);
1982 error_build("%d message%s for %s",
1983 count, count > 1 ? "s" : "", buf);
1985 error_complete(0, 0, ".");
1987 error_complete(0, 0, " (%d bytes).", bytes);
1991 /* these are pointless in normal daemon mode */
1992 if (pass == 1 && (run.poll_interval == 0 || outlevel == O_VERBOSE))
1993 error(0, 0, "No mail for %s", buf);
1996 /* very important, this is where we leave the do loop */
2002 if (new == -1 || ctl->fetchall)
2004 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
2009 flag force_retrieval;
2012 * What forces this code is that in POP2 and
2013 * IMAP2bis you can't fetch a message without
2014 * having it marked `seen'. In POP3 and IMAP4, on the
2015 * other hand, you can (peek_capable is set by
2016 * each driver module to convey this; it's not a
2017 * method constant because of the difference between
2018 * IMAP2bis and IMAP4).
2020 * The result of being unable to peek is that if there's
2021 * any kind of transient error (DNS lookup failure, or
2022 * sendmail refusing delivery due to process-table limits)
2023 * the message will be marked "seen" on the server without
2024 * having been delivered. This is not a big problem if
2025 * fetchmail is running in foreground, because the user
2026 * will see a "skipped" message when it next runs and get
2029 * But in daemon mode this leads to the message
2030 * being silently ignored forever. This is not
2033 * We compensate for this by checking the error
2034 * count from the previous pass and forcing all
2035 * messages to be considered new if it's nonzero.
2037 force_retrieval = !peek_capable && (ctl->errcount > 0);
2039 /* read, forward, and delete messages */
2040 for (num = 1; num <= count; num++)
2042 flag toolarge = NUM_NONZERO(ctl->limit)
2043 && msgsizes && (msgsizes[num-1] > ctl->limit);
2044 flag fetch_it = !toolarge
2045 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
2046 flag suppress_delete = FALSE;
2047 flag suppress_forward = FALSE;
2048 flag suppress_readbody = FALSE;
2049 flag retained = FALSE;
2052 * This check copes with Post Office/NT's
2053 * annoying habit of randomly prepending bogus
2054 * LIST items of length -1. Patrick Audley
2055 * <paudley@pobox.com> tells us: LIST shows a
2056 * size of -1, RETR and TOP return "-ERR
2057 * System error - couldn't open message", and
2058 * DELE succeeds but doesn't actually delete
2061 if (msgsizes && msgsizes[num-1] == -1)
2063 if (outlevel >= O_VERBOSE)
2065 "Skipping message %d, length -1",
2070 /* we may want to reject this message if it's old */
2073 if (outlevel > O_SILENT)
2075 error_build("skipping message %d", num);
2077 error_build(" (oversized, %d bytes)",
2083 flag wholesize = !protocol->fetch_body;
2085 /* request a message */
2086 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
2090 /* -1 means we didn't see a size in the response */
2091 if (len == -1 && msgsizes)
2093 len = msgsizes[num - 1];
2097 if (outlevel > O_SILENT)
2099 error_build("reading message %d of %d",
2103 error_build(" (%d %sbytes)",
2104 len, wholesize ? "" : "header ");
2105 if (outlevel == O_VERBOSE)
2106 error_complete(0, 0, "");
2111 /* later we'll test for this before closing */
2112 sinkfp = (FILE *)NULL;
2115 * Read the message headers and ship them to the
2118 ok = readheaders(sock, len, msgsizes[num-1],
2120 if (ok == PS_RETAINED)
2121 suppress_forward = retained = TRUE;
2122 else if (ok == PS_TRANSIENT)
2123 suppress_delete = suppress_forward = TRUE;
2124 else if (ok == PS_REFUSED)
2125 suppress_forward = TRUE;
2126 else if (ok == PS_TRUNCATED)
2127 suppress_readbody = TRUE;
2132 * If we're using IMAP4 or something else that
2133 * can fetch headers separately from bodies,
2134 * it's time to request the body now. This
2135 * fetch may be skipped if we got an anti-spam
2136 * or other PS_REFUSED error response during
2139 if (protocol->fetch_body && !suppress_readbody)
2141 if (outlevel == O_VERBOSE)
2142 fputc('\n', stderr);
2144 if ((ok = (protocol->trail)(sock, ctl, num)))
2147 if (!suppress_forward)
2149 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
2151 if (outlevel > O_SILENT && !wholesize)
2152 error_build(" (%d body bytes) ", len);
2156 /* process the body now */
2159 if (suppress_readbody)
2161 /* When readheaders returns PS_TRUNCATED,
2162 the body (which has no content
2163 has already been read by readheaders,
2164 so we say readbody returned PS_SUCCESS */
2174 if (ok == PS_TRANSIENT)
2175 suppress_delete = suppress_forward = TRUE;
2179 /* tell server we got it OK and resynchronize */
2180 if (protocol->trail)
2182 if (outlevel == O_VERBOSE)
2183 fputc('\n', stderr);
2185 ok = (protocol->trail)(sock, ctl, num);
2191 /* count # messages forwarded on this pass */
2192 if (!suppress_forward)
2196 * Check to see if the numbers matched?
2198 * Yes, some servers foo this up horribly.
2199 * All IMAP servers seem to get it right, and
2200 * so does Eudora QPOP at least in 2.xx
2203 * Microsoft Exchange gets it completely
2204 * wrong, reporting compressed rather than
2205 * actual sizes (so the actual length of
2206 * message is longer than the reported size).
2207 * Another fine example of Microsoft brain death!
2209 * Some older POP servers, like the old UCB
2210 * POP server and the pre-QPOP QUALCOMM
2211 * versions, report a longer size in the LIST
2212 * response than actually gets shipped up.
2213 * It's unclear what is going on here, as the
2214 * QUALCOMM server (at least) seems to be
2215 * reporting the on-disk size correctly.
2217 if (msgsizes && msglen != msgsizes[num-1])
2219 if (outlevel >= O_VERBOSE)
2221 "message %d was not the expected length (%d != %d)",
2222 num, msglen, msgsizes[num-1]);
2225 /* end-of-message processing starts here */
2231 /* close the delivery pipe, we'll reopen before next message */
2233 rc = pclose(sinkfp);
2236 signal(SIGCHLD, sigchld);
2239 error(0, -1, "MDA exited abnormally or returned nonzero status");
2243 else if (!suppress_forward)
2245 /* write message terminator */
2246 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2248 error(0, -1, "SMTP listener refused delivery");
2250 suppress_delete = TRUE;
2258 * At this point in flow of control, either
2259 * we've bombed on a protocol error or had
2260 * delivery refused by the SMTP server
2261 * (unlikely -- I've never seen it) or we've
2262 * seen `accepted for delivery' and the
2263 * message is shipped. It's safe to mark the
2264 * message seen and delete it on the server
2268 /* tell the UID code we've seen this */
2273 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2274 if (sdp->val.status.num == num)
2275 sdp->val.status.mark = UID_SEEN;
2278 /* maybe we delete this message now? */
2281 if (outlevel > O_SILENT)
2282 error_complete(0, 0, " retained");
2284 else if (protocol->delete
2286 && (fetch_it ? !ctl->keep : ctl->flush))
2289 if (outlevel > O_SILENT)
2290 error_complete(0, 0, " flushed");
2291 ok = (protocol->delete)(sock, ctl, num);
2295 delete_str(&ctl->newsaved, num);
2296 #endif /* POP3_ENABLE */
2298 else if (outlevel > O_SILENT)
2299 error_complete(0, 0, " not flushed");
2301 /* perhaps this as many as we're ready to handle */
2302 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2308 * Only re-poll if we had some actual forwards, allowed
2309 * deletions and had no errors.
2310 * Otherwise it is far too easy to get into infinite loops.
2312 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2316 ok = (protocol->logout_cmd)(sock, ctl);
2318 * Hmmmm...arguably this would be incorrect if we had fetches but
2319 * no dispatches (due to oversized messages, etc.)
2322 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2327 if (ok != 0 && ok != PS_SOCKET)
2328 (protocol->logout_cmd)(sock, ctl);
2332 msg = (char *)NULL; /* sacrifice to -Wall */
2339 msg = "authorization";
2342 msg = "missing or bad RFC822 header";
2348 msg = "client/server synchronization";
2351 msg = "client/server protocol";
2354 msg = "lock busy on server";
2357 msg = "SMTP transaction";
2363 error(0, 0, "undefined");
2366 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2367 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2368 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2369 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2372 /* execute post-initialization command, if any */
2373 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2377 sprintf(buf, "post-connection command failed with status %d", ok);
2379 if (ok == PS_SUCCESS)
2383 signal(SIGALRM, sigsave);
2387 #if defined(HAVE_STDARG_H)
2388 void gen_send(int sock, const char *fmt, ... )
2389 /* assemble command in printf(3) style and send to the server */
2391 void gen_send(sock, fmt, va_alist)
2392 /* assemble command in printf(3) style and send to the server */
2393 int sock; /* socket to which server is connected */
2394 const char *fmt; /* printf-style format */
2398 char buf [MSGBUFSIZE+1];
2401 if (protocol->tagged)
2402 (void) sprintf(buf, "%s ", GENSYM);
2406 #if defined(HAVE_STDARG_H)
2411 #ifdef HAVE_VSNPRINTF
2412 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2414 vsprintf(buf + strlen(buf), fmt, ap);
2418 strcat(buf, "\r\n");
2419 SockWrite(sock, buf, strlen(buf));
2421 if (outlevel == O_VERBOSE)
2425 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2429 sp = cp + strlen(shroud);
2435 buf[strlen(buf)-2] = '\0';
2436 error(0, 0, "%s> %s", protocol->name, buf);
2440 int gen_recv(sock, buf, size)
2441 /* get one line of input from the server */
2442 int sock; /* socket to which server is connected */
2443 char *buf; /* buffer to receive input */
2444 int size; /* length of buffer */
2446 int oldphase = phase; /* we don't have to be re-entrant */
2448 phase = SERVER_WAIT;
2449 set_timeout(mytimeout);
2450 if (SockRead(sock, buf, size) == -1)
2459 if (buf[strlen(buf)-1] == '\n')
2460 buf[strlen(buf)-1] = '\0';
2461 if (buf[strlen(buf)-1] == '\r')
2462 buf[strlen(buf)-1] = '\0';
2463 if (outlevel == O_VERBOSE)
2464 error(0, 0, "%s< %s", protocol->name, buf);
2470 #if defined(HAVE_STDARG_H)
2471 int gen_transact(int sock, char *fmt, ... )
2472 /* assemble command in printf(3) style, send to server, accept a response */
2474 int gen_transact(int sock, fmt, va_alist)
2475 /* assemble command in printf(3) style, send to server, accept a response */
2476 int sock; /* socket to which server is connected */
2477 const char *fmt; /* printf-style format */
2482 char buf [MSGBUFSIZE+1];
2484 int oldphase = phase; /* we don't have to be re-entrant */
2486 phase = SERVER_WAIT;
2488 if (protocol->tagged)
2489 (void) sprintf(buf, "%s ", GENSYM);
2493 #if defined(HAVE_STDARG_H)
2498 #ifdef HAVE_VSNPRINTF
2499 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2501 vsprintf(buf + strlen(buf), fmt, ap);
2505 strcat(buf, "\r\n");
2506 SockWrite(sock, buf, strlen(buf));
2508 if (outlevel == O_VERBOSE)
2512 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2516 sp = cp + strlen(shroud);
2522 buf[strlen(buf)-1] = '\0';
2523 error(0, 0, "%s> %s", protocol->name, buf);
2526 /* we presume this does its own response echoing */
2527 ok = (protocol->parse_response)(sock, buf);
2533 /* driver.c ends here */