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
48 #endif /* HAVE_RES_SEARCH */
51 #if defined (__bsdi__)
52 #include <des.h> /* order of includes matters */
54 #define krb_get_err_text(e) (krb_err_txt[e])
56 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
57 #define krb_get_err_text(e) (krb_err_txt[e])
63 #endif /* ! defined (__FreeBSD__) */
64 #endif /* ! defined (__bsdi__) */
65 #include <netinet/in.h>
67 #endif /* KERBEROS_V4 */
71 #endif /* KEREROS_V5 */
73 #include "fetchmail.h"
77 /* BSD portability hack...I know, this is an ugly place to put it */
78 #if !defined(SIGCHLD) && defined(SIGCLD)
79 #define SIGCHLD SIGCLD
83 #define SMTP_PORT "smtp" /* standard SMTP service port */
85 #define SMTP_PORT 25 /* standard SMTP service port */
88 #ifndef strstr /* glibc-2.1 declares this as a macro */
89 extern char *strstr(); /* needed on sysV68 R3V7.1. */
92 int fetchlimit; /* how often to tear down the server connection */
93 int batchcount; /* count of messages sent in current batch */
94 flag peek_capable; /* can we peek for better error recovery? */
95 int pass; /* how many times have we re-polled? */
97 static const struct method *protocol;
98 static jmp_buf restart;
102 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
104 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
105 static int mytimeout; /* value of nonreponse timeout */
106 static int msglen; /* actual message length */
107 static int mimemsg; /* bitmask indicating MIME body-type */
109 /* use these to track what was happening when the nonresponse timer fired */
110 #define GENERAL_WAIT 0 /* unknown wait type */
111 #define SERVER_WAIT 1 /* waiting for mailserver response */
112 #define LISTENER_WAIT 2 /* waiting for listener initialization */
113 #define FORWARDING_WAIT 3 /* waiting for listener response */
116 static void set_timeout(int timeleft)
117 /* reset the nonresponse-timeout */
120 struct itimerval ntimeout;
122 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
123 ntimeout.it_value.tv_sec = timeleft;
124 ntimeout.it_value.tv_usec = 0;
125 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
129 static void timeout_handler (int signal)
130 /* handle server-timeout SIGALRM signal */
135 #define XMIT_ACCEPT 1
136 #define XMIT_REJECT 2
137 #define XMIT_ANTISPAM 3
138 static int accept_count, reject_count;
140 static void map_name(name, ctl, xmit_names)
141 /* add given name to xmit_names if it matches declared localnames */
142 const char *name; /* name to map */
143 struct query *ctl; /* list of permissible aliases */
144 struct idlist **xmit_names; /* list of recipient names parsed out */
150 lname = idpair_find(&ctl->localnames, name+off);
151 if (!lname && ctl->wildcard)
154 if (lname != (char *)NULL)
156 if (outlevel == O_VERBOSE)
157 error(0, 0, "mapped %s to local %s", name, lname);
158 save_str(xmit_names, lname, XMIT_ACCEPT);
163 void find_server_names(hdr, ctl, xmit_names)
164 /* parse names out of a RFC822 header into an ID list */
165 const char *hdr; /* RFC822 header in question */
166 struct query *ctl; /* list of permissible aliases */
167 struct idlist **xmit_names; /* list of recipient names parsed out */
169 if (hdr == (char *)NULL)
175 for (cp = nxtaddr(hdr);
182 * If the name of the user begins with a qmail virtual
183 * domain prefix, ignore the prefix. Doing this here
184 * means qvirtual will work either with ordinary name
185 * mapping or with a localdomains option.
187 if (ctl->server.qvirtual)
189 int sl = strlen(ctl->server.qvirtual);
191 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
195 if ((atsign = strchr(cp, '@'))) {
199 * Does a trailing segment of the hostname match something
200 * on the localdomains list? If so, save the whole name
203 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
206 rhs = atsign + (strlen(atsign) - strlen(idp->id));
208 (rhs[-1] == '.' || rhs[-1] == '@') &&
209 strcasecmp(rhs, idp->id) == 0)
211 if (outlevel == O_VERBOSE)
212 error(0, 0, "passed through %s matching %s",
214 save_str(xmit_names, cp, XMIT_ACCEPT);
220 /* if we matched a local domain, idp != NULL */
224 * Check to see if the right-hand part is an alias
225 * or MX equivalent of the mailserver. If it's
226 * not, skip this name. If it is, we'll keep
227 * going and try to find a mapping to a client name.
229 if (!is_host_alias(atsign+1, ctl))
231 save_str(xmit_names, cp, XMIT_REJECT);
237 map_name(cp, ctl, xmit_names);
244 static char *parse_received(struct query *ctl, char *bufp)
245 /* try to extract real address from the Received line */
246 /* If a valid Received: line is found, we return the full address in
247 * a buffer which can be parsed from nxtaddr(). This is to ansure that
248 * the local domain part of the address can be passed along in
249 * find_server_names() if it contains one.
250 * Note: We should return a dummy header containing the address
251 * which makes nxtaddr() behave correctly.
254 char *ok = (char *)NULL;
255 static char rbuf[HOSTLEN + USERNAMELEN + 4];
258 * Try to extract the real envelope addressee. We look here
259 * specifically for the mailserver's Received line.
260 * Note: this will only work for sendmail, or an MTA that
261 * shares sendmail's convention for embedding the envelope
262 * address in the Received line. Sendmail itself only
263 * does this when the mail has a single recipient.
265 if ((ok = strstr(bufp, "by ")) && isspace(ok[-1]))
269 /* extract space-delimited token after "by " */
270 for (sp = ok + 3; isspace(*sp); sp++)
273 for (; !isspace(*sp); sp++)
278 * If it's a DNS name of the mail server, look for the
279 * recipient name after a following "for". Otherwise
282 if (is_host_alias(rbuf, ctl) &&
283 (ok = strstr(sp, "for ")) &&
288 *tp++ = ':'; /* Here is the hack. This is to be friend */
289 *tp++ = ' '; /* with nxtaddr()... */
292 while (*sp == '@') /* skip routes */
293 while (*sp && *sp++ != ':')
295 while (*sp && *sp != '>' && *sp != ';')
300 /* uh oh -- whitespace here can't be right! */
306 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
316 if (outlevel == O_VERBOSE) {
317 char *lf = rbuf + strlen(rbuf)-1;
319 error(0, 0, "found Received address `%s'", rbuf+2);
326 static int smtp_open(struct query *ctl)
327 /* try to open a socket to the appropriate SMTP server for this query */
329 /* maybe it's time to close the socket in order to force delivery */
330 if (NUM_NONZERO(ctl->batchlimit) && (ctl->smtp_socket != -1) && batchcount++ == ctl->batchlimit)
332 close(ctl->smtp_socket);
333 ctl->smtp_socket = -1;
337 /* if no socket to any SMTP host is already set up, try to open one */
338 if (ctl->smtp_socket == -1)
341 * RFC 1123 requires that the domain name in HELO address is a
342 * "valid principal domain name" for the client host. If we're
343 * running in invisible mode, violate this with malice
344 * aforethought in order to make the Received headers and
345 * logging look right.
347 * In fact this code relies on the RFC1123 requirement that the
348 * SMTP listener must accept messages even if verification of the
349 * HELO name fails (RFC1123 section 5.2.5, paragraph 2).
351 * How we compute the true mailhost name to pass to the
352 * listener doesn't affect behavior on RFC1123- violating
353 * listeners that check for name match; we're going to lose
354 * on those anyway because we can never give them a name
355 * that matches the local machine fetchmail is running on.
356 * What it will affect is the listener's logging.
359 char *id_me = run.invisible ? ctl->server.truename : fetchmailhost;
360 int oldphase = phase;
365 * Run down the SMTP hunt list looking for a server that's up.
366 * Use both explicit hunt entries (value TRUE) and implicit
367 * (default) ones (value FALSE).
370 phase = LISTENER_WAIT;
372 set_timeout(ctl->server.timeout);
373 for (idp = ctl->smtphunt; idp; idp = idp->next)
375 char *cp, *parsed_host = alloca(strlen(idp->id) + 1);
377 char *portnum = SMTP_PORT;
379 int portnum = SMTP_PORT;
382 ctl->smtphost = idp->id; /* remember last host tried. */
384 strcpy(parsed_host, idp->id);
385 if ((cp = strrchr(parsed_host, '/')))
395 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
398 /* first, probe for ESMTP */
399 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
400 SMTP_ehlo(ctl->smtp_socket, id_me,
401 &ctl->server.esmtp_options) == SM_OK)
405 * RFC 1869 warns that some listeners hang up on a failed EHLO,
406 * so it's safest not to assume the socket will still be good.
408 close(ctl->smtp_socket);
409 ctl->smtp_socket = -1;
411 /* if opening for ESMTP failed, try SMTP */
412 if ((ctl->smtp_socket = SockOpen(parsed_host,portnum,NULL)) == -1)
415 if (SMTP_ok(ctl->smtp_socket) == SM_OK &&
416 SMTP_helo(ctl->smtp_socket, id_me) == SM_OK)
419 close(ctl->smtp_socket);
420 ctl->smtp_socket = -1;
426 if (outlevel >= O_VERBOSE && ctl->smtp_socket != -1)
427 error(0, 0, "forwarding to %s", ctl->smtphost);
429 return(ctl->smtp_socket);
432 /* these are shared by stuffline, readheaders and readbody */
434 static RETSIGTYPE (*sigchld)();
435 static int sizeticker;
437 static int stuffline(struct query *ctl, char *buf)
438 /* ship a line to the given control block's output sink (SMTP server or MDA) */
443 /* The line may contain NUL characters. Find the last char to use
444 * -- the real line termination is the sequence "\n\0".
447 while ((last += strlen(last)) && (last[-1] != '\n'))
450 /* fix message lines that have only \n termination (for qmail) */
453 if (last - 1 == buf || last[-2] != '\r')
462 phase = FORWARDING_WAIT;
465 * SMTP byte-stuffing. We only do this if the protocol does *not*
466 * use .<CR><LF> as EOM. If it does, the server will already have
467 * decorated any . lines it sends back up.
470 if (protocol->delimited) /* server has already byte-stuffed */
475 /* writing to SMTP, leave the byte-stuffing in place */;
477 else /* if (!protocol->delimited) -- not byte-stuffed already */
480 SockWrite(ctl->smtp_socket, buf, 1); /* byte-stuff it */
482 /* leave it alone */;
485 /* we may need to strip carriage returns */
490 for (sp = tp = buf; sp < last; sp++)
499 n = fwrite(buf, 1, last - buf, sinkfp);
500 else if (ctl->smtp_socket != -1)
501 n = SockWrite(ctl->smtp_socket, buf, last - buf);
509 static void sanitize(s)
510 /* replace unsafe shellchars by an _ */
513 static char *ok_chars = " 1234567890!@%-_=+:,./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
516 for (cp = s; *(cp += strspn(cp, ok_chars)); /* NO INCREMENT */)
521 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
523 static int readheaders(sock, fetchlen, reallen, ctl, num)
524 /* read message headers and ship to SMTP or MDA */
525 int sock; /* to which the server is connected */
526 long fetchlen; /* length of message according to fetch response */
527 long reallen; /* length of message according to getsizes */
528 struct query *ctl; /* query control record */
529 int num; /* index of message */
534 struct addrblk *next;
536 struct addrblk *to_addrchain = NULL;
537 struct addrblk **to_chainptr = &to_addrchain;
538 struct addrblk *resent_to_addrchain = NULL;
539 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
541 char buf[MSGBUFSIZE+1];
542 char return_path[HOSTLEN + USERNAMELEN + 4];
543 int from_offs, reply_to_offs, resent_from_offs;
544 int app_from_offs, sender_offs, resent_sender_offs;
546 char *headers, *received_for, *destaddr, *rcv, *cp;
547 int n, linelen, oldlen, ch, remaining, skipcount;
548 struct idlist *idp, *xmit_names;
549 flag good_addresses, bad_addresses, has_nuls;
550 flag no_local_matches = FALSE;
555 has_nuls = headers_ok = FALSE;
556 return_path[0] = '\0';
557 olderrs = ctl->errcount;
559 /* read message headers */
560 headers = received_for = NULL;
561 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
562 sender_offs = resent_sender_offs = env_offs = -1;
568 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
572 line = xmalloc(sizeof(buf));
576 set_timeout(ctl->server.timeout);
577 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
587 /* lines may not be properly CRLF terminated; fix this for qmail */
590 cp = buf + strlen(buf) - 1;
591 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
600 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
604 /* check for end of headers */
608 has_nuls = (linelen != strlen(line));
610 goto process_headers;
614 * Check for end of message immediately. If one of your folders
615 * has been mangled, the delimiter may occur directly after the
618 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
621 has_nuls = (linelen != strlen(line));
622 goto process_headers;
625 /* we may need to grab RFC822 continuations */
626 ((ch = SockPeek(sock)) == ' ' || ch == '\t');
628 /* write the message size dots */
629 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
631 sizeticker += linelen;
632 while (sizeticker >= SIZETICKER)
635 sizeticker -= SIZETICKER;
639 /* we see an ordinary (non-header, non-message-delimiter line */
640 has_nuls = (linelen != strlen(line));
643 * The University of Washington IMAP server (the reference
644 * implementation of IMAP4 written by Mark Crispin) relies
645 * on being able to keep base-UID information in a special
646 * message at the head of the mailbox. This message should
647 * neither be deleted nor forwarded.
651 * We disable this check under POP2 because there's no way to
652 * prevent deletion of the message. So at least we ought to
653 * forward it to the user so he or she will have some clue
654 * that things have gone awry.
656 if (protocol->port != 109)
657 #endif /* POP2_ENABLE */
658 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
665 * This code prevents fetchmail from becoming an accessory after
666 * the fact to upstream sendmails with the `E' option on. It also
667 * copes with certain brain-dead POP servers (like NT's) that pass
668 * through Unix from_ lines.
670 * Either of these bugs can result in a non-RFC822 line at the
671 * beginning of the headers. If fetchmail just passes it
672 * through, the client listener may think the message has *no*
673 * headers (since the first) line it sees doesn't look
674 * RFC822-conformant) and fake up a set.
676 * What the user would see in this case is bogus (synthesized)
677 * headers, followed by a blank line, followed by the >From,
678 * followed by the real headers, followed by a blank line,
681 * We forestall this lossage by tossing anything that looks
682 * like an escaped or passed-through From_ line in headers.
683 * These aren't RFC822 so our conscience is clear...
685 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
692 * If we see a Status line, it may have been inserted by an MUA
693 * on the mail host, or it may have been inserted by the server
694 * program after the headers in the transaction stream. This
695 * can actually hose some new-mail notifiers such as xbuffy,
696 * which assumes any Status line came from a *local* MDA and
697 * therefore indicates that the message has been seen.
699 * Some buggy POP servers (including at least the 3.3(20)
700 * version of the one distributed with IMAP) insert empty
701 * Status lines in the transaction stream; we'll chuck those
702 * unconditionally. Nonempty ones get chucked if the user
703 * turns on the dropstatus flag.
708 if (!strncasecmp(line, "Status:", 7))
710 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
715 while (*cp && isspace(*cp)) cp++;
716 if (!*cp || ctl->dropstatus)
725 line = reply_hack(line, ctl->server.truename);
728 * OK, this is messy. If we're forwarding by SMTP, it's the
729 * SMTP-receiver's job (according to RFC821, page 22, section
730 * 4.1.1) to generate a Return-Path line on final delivery.
731 * The trouble is, we've already got one because the
732 * mailserver's SMTP thought *it* was responsible for final
735 * Stash away the contents of Return-Path for use in generating
736 * MAIL FROM later on, then prevent the header from being saved
737 * with the others. In effect, we strip it off here.
739 * If the SMTP server conforms to the standards, and fetchmail gets the
740 * envelope sender from the Return-Path, the new Return-Path should be
741 * exactly the same as the original one.
743 * We do *not* want to ignore empty Return-Path headers. These should
744 * be passed through as a way of indicating that a message should
745 * not trigger bounces if delivery fails. What we *do* need to do is
746 * make sure we never try to rewrite such a blank Return-Path. We
747 * handle this with a check for <> in the rewrite logic.
749 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
751 strcpy(return_path, cp);
760 oldlen = strlen(line);
761 headers = xmalloc(oldlen + 1);
762 (void) strcpy(headers, line);
770 newlen = oldlen + strlen(line);
771 headers = (char *) realloc(headers, newlen + 1);
772 if (headers == NULL) {
776 strcpy(headers + oldlen, line);
778 line = headers + oldlen;
782 if (!strncasecmp("From:", line, 5))
783 from_offs = (line - headers);
784 else if (!strncasecmp("Reply-To:", line, 9))
785 reply_to_offs = (line - headers);
786 else if (!strncasecmp("Resent-From:", line, 12))
787 resent_from_offs = (line - headers);
788 else if (!strncasecmp("Apparently-From:", line, 16))
789 app_from_offs = (line - headers);
790 else if (!strncasecmp("Sender:", line, 7))
791 sender_offs = (line - headers);
792 else if (!strncasecmp("Resent_Sender:", line, 14))
793 resent_sender_offs = (line - headers);
795 else if (!strncasecmp("Message-Id:", buf, 11))
797 if (ctl->server.uidl)
801 buf[IDLEN+12] = 0; /* prevent stack overflow */
802 sscanf(buf+12, "%s", id);
803 if (!str_find( &ctl->newsaved, num))
805 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
806 new->val.status.num = num;
811 else if (!MULTIDROP(ctl))
814 else if (!strncasecmp("To:", line, 3)
815 || !strncasecmp("Cc:", line, 3)
816 || !strncasecmp("Bcc:", line, 4)
817 || !strncasecmp("Apparently-To:", line, 14))
819 *to_chainptr = xmalloc(sizeof(struct addrblk));
820 (*to_chainptr)->offset = (line - headers);
821 to_chainptr = &(*to_chainptr)->next;
825 else if (!strncasecmp("Resent-To:", line, 10)
826 || !strncasecmp("Resent-Cc:", line, 10)
827 || !strncasecmp("Resent-Bcc:", line, 11))
829 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
830 (*resent_to_chainptr)->offset = (line - headers);
831 resent_to_chainptr = &(*resent_to_chainptr)->next;
832 *resent_to_chainptr = NULL;
835 else if (ctl->server.envelope != STRING_DISABLED)
837 if (ctl->server.envelope
838 && strcasecmp(ctl->server.envelope, "Received"))
840 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
842 strlen(ctl->server.envelope)))
844 if (skipcount++ != ctl->server.envskip)
846 env_offs = (line - headers);
849 else if (!received_for && !strncasecmp("Received:", line, 9))
851 if (skipcount++ != ctl->server.envskip)
853 received_for = parse_received(ctl, line);
860 * We want to detect this early in case there are so few headers that the
861 * dispatch logic barfs.
865 if (outlevel > O_SILENT)
866 error(0,0,"message delimiter found while scanning headers");
870 * Hack time. If the first line of the message was blank, with no headers
871 * (this happens occasionally due to bad gatewaying software) cons up
872 * a set of fake headers.
874 * If you modify the fake header template below, be sure you don't
875 * make either From or To address @-less, otherwise the reply_hack
876 * logic will do bad things.
878 if (headers == (char *)NULL)
881 snprintf(buf, sizeof(buf),
884 #endif /* HAVE_SNPRINTF */
885 "From: <FETCHMAIL-DAEMON@%s>\r\nTo: %s@localhost\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
886 fetchmailhost, user, ctl->remotename, ctl->server.truename);
887 headers = xstrdup(buf);
891 * We can now process message headers before reading the text.
892 * In fact we have to, as this will tell us where to forward to.
895 /* Decode MIME encoded headers. We MUST do this before
896 * looking at the Content-Type / Content-Transfer-Encoding
897 * headers (RFC 2046).
899 if (ctl->mimedecode) {
900 UnMimeHeader(headers);
902 /* Check for MIME headers indicating possible 8-bit data */
903 mimemsg = MimeBodyType(headers, ctl->mimedecode);
906 * If there is a Return-Path address on the message, this was
907 * almost certainly the MAIL FROM address given the originating
908 * sendmail. This is the best thing to use for logging the
909 * message origin (it sets up the right behavior for bounces and
910 * mailing lists). Otherwise, fall down to the next available
911 * envelope address (which is the most probable real sender).
912 * *** The order is important! ***
913 * This is especially useful when receiving mailing list
914 * messages in multidrop mode. if a local address doesn't
915 * exist, the bounce message won't be returned blindly to the
916 * author or to the list itself but rather to the list manager
917 * (ex: specified by "Sender:") wich is less anoying. This is
918 * true for most mailing list packages.
920 if( !return_path[0] ){
922 if (resent_sender_offs >= 0 && (ap = nxtaddr(headers + resent_sender_offs)));
923 else if (sender_offs >= 0 && (ap = nxtaddr(headers + sender_offs)));
924 else if (resent_from_offs >= 0 && (ap = nxtaddr(headers + resent_from_offs)));
925 else if (from_offs >= 0 && (ap = nxtaddr(headers + from_offs)));
926 else if (reply_to_offs >= 0 && (ap = nxtaddr(headers + reply_to_offs)));
927 else if (app_from_offs >= 0 && (ap = nxtaddr(headers + app_from_offs)));
928 if (ap) strcpy( return_path, ap );
931 /* cons up a list of local recipients */
932 xmit_names = (struct idlist *)NULL;
933 bad_addresses = good_addresses = accept_count = reject_count = 0;
934 /* is this a multidrop box? */
937 if (env_offs > -1) /* We have the actual envelope addressee */
938 find_server_names(headers + env_offs, ctl, &xmit_names);
939 else if (received_for)
941 * We have the Received for addressee.
942 * It has to be a mailserver address, or we
943 * wouldn't have got here.
944 * We use find_server_names() to let local
945 * hostnames go through.
947 find_server_names(received_for, ctl, &xmit_names);
950 * We haven't extracted the envelope address.
951 * So check all the "Resent-To" header addresses if
952 * they exist. If and only if they don't, consider
955 register struct addrblk *nextptr;
956 if (resent_to_addrchain) {
957 /* delete the "To" chain and substitute it
958 * with the "Resent-To" list
960 while (to_addrchain) {
961 nextptr = to_addrchain->next;
963 to_addrchain = nextptr;
965 to_addrchain = resent_to_addrchain;
966 resent_to_addrchain = NULL;
968 /* now look for remaining adresses */
969 while (to_addrchain) {
970 find_server_names(headers+to_addrchain->offset, ctl, &xmit_names);
971 nextptr = to_addrchain->next;
973 to_addrchain = nextptr;
978 no_local_matches = TRUE;
979 save_str(&xmit_names, run.postmaster, XMIT_ACCEPT);
980 if (outlevel == O_VERBOSE)
982 "no local matches, forwarding to %s",
986 else /* it's a single-drop box, use first localname */
987 save_str(&xmit_names, ctl->localnames->id, XMIT_ACCEPT);
991 * Time to either address the message or decide we can't deliver it yet.
993 if (ctl->errcount > olderrs) /* there were DNS errors above */
995 if (outlevel == O_VERBOSE)
996 error(0,0, "forwarding and deletion suppressed due to DNS errors");
998 free_str_list(&xmit_names);
999 return(PS_TRANSIENT);
1001 else if (ctl->mda) /* we have a declared MDA */
1003 int length = 0, fromlen = 0, nameslen = 0;
1004 char *names = NULL, *before, *after, *from = NULL;
1006 for (idp = xmit_names; idp; idp = idp->next)
1007 if (idp->val.status.mark == XMIT_ACCEPT)
1010 destaddr = "localhost";
1012 length = strlen(ctl->mda);
1013 before = xstrdup(ctl->mda);
1015 /* get user addresses for %T (or %s for backward compatibility) */
1016 if (strstr(before, "%s") || strstr(before, "%T"))
1019 * We go through this in order to be able to handle very
1020 * long lists of users and (re)implement %s.
1023 for (idp = xmit_names; idp; idp = idp->next)
1024 if (idp->val.status.mark == XMIT_ACCEPT)
1025 nameslen += (strlen(idp->id) + 1); /* string + ' ' */
1027 names = (char *)xmalloc(nameslen + 1); /* account for '\0' */
1029 for (idp = xmit_names; idp; idp = idp->next)
1030 if (idp->val.status.mark == XMIT_ACCEPT)
1032 strcat(names, idp->id);
1035 names[--nameslen] = '\0'; /* chop trailing space */
1037 /* sanitize names in order to contain *only* harmless shell chars */
1041 /* get From address for %F */
1042 if (strstr(before, "%F"))
1044 from = xstrdup(return_path);
1046 /* sanitize from in order to contain *only* harmless shell chars */
1049 fromlen = strlen(from);
1052 /* do we have to build an mda string? */
1053 if (names || from) {
1058 /* find length of resulting mda string */
1060 while (sp = strstr(sp, "%s")) {
1061 length += nameslen - 2; /* subtract %s */
1065 while (sp = strstr(sp, "%T")) {
1066 length += nameslen - 2; /* subtract %T */
1070 while (sp = strstr(sp, "%F")) {
1071 length += fromlen - 2; /* subtract %F */
1075 after = xmalloc(length + 1);
1077 /* copy mda source string to after, while expanding %[sTF] */
1078 for (dp = after, sp = before; *dp = *sp; dp++, sp++) {
1079 if (sp[0] != '%') continue;
1081 /* need to expand? BTW, no here overflow, because in
1082 ** the worst case (end of string) sp[1] == '\0' */
1083 if (sp[1] == 's' || sp[1] == 'T') {
1086 sp++; /* position sp over [sT] */
1087 dp--; /* adjust dp */
1088 } else if (sp[1] == 'F') {
1091 sp++; /* position sp over F */
1092 dp--; /* adjust dp */
1111 if (outlevel == O_VERBOSE)
1112 error(0, 0, "about to deliver with: %s", before);
1116 * Arrange to run with user's permissions if we're root.
1117 * This will initialize the ownership of any files the
1118 * MDA creates properly. (The seteuid call is available
1119 * under all BSDs and Linux)
1122 #endif /* HAVE_SETEUID */
1124 sinkfp = popen(before, "w");
1129 /* this will fail quietly if we didn't start as root */
1131 #endif /* HAVE_SETEUID */
1135 error(0, 0, "MDA open failed");
1137 free_str_list(&xmit_names);
1141 sigchld = signal(SIGCHLD, SIG_DFL);
1145 char *ap, options[MSGBUFSIZE], addr[128];
1147 /* build a connection to the SMTP listener */
1148 if ((smtp_open(ctl) == -1))
1150 error(0, errno, "SMTP connect to %s failed",
1151 ctl->smtphost ? ctl->smtphost : "localhost");
1153 free_str_list(&xmit_names);
1158 * Compute ESMTP options.
1161 if (ctl->server.esmtp_options & ESMTP_8BITMIME) {
1162 if (ctl->pass8bits || (mimemsg & MSG_IS_8BIT))
1163 strcpy(options, " BODY=8BITMIME");
1164 else if (mimemsg & MSG_IS_7BIT)
1165 strcpy(options, " BODY=7BIT");
1168 if ((ctl->server.esmtp_options & ESMTP_SIZE) && reallen > 0)
1169 sprintf(options + strlen(options), " SIZE=%ld", reallen);
1172 * Try to get the SMTP listener to take the Return-Path
1173 * address as MAIL FROM . If it won't, fall back on the
1174 * calling-user ID. This won't affect replies, which use the
1175 * header From address anyway.
1177 * RFC 1123 requires that the domain name part of the
1178 * MAIL FROM address be "canonicalized", that is a
1179 * FQDN or MX but not a CNAME. We'll assume the From
1180 * header is already in this form here (it certainly
1181 * is if rewrite is on). RFC 1123 is silent on whether
1182 * a nonexistent hostname part is considered canonical.
1184 * This is a potential problem if the MTAs further upstream
1185 * didn't pass canonicalized From/Return-Path lines, *and* the
1186 * local SMTP listener insists on them.
1188 * None of these error conditions generates bouncemail. Comments
1189 * below explain for each case why this is so.
1191 ap = (return_path[0]) ? return_path : user;
1192 if (SMTP_from(ctl->smtp_socket, ap, options) != SM_OK)
1194 int smtperr = atoi(smtp_response);
1196 if (str_find(&ctl->antispam, smtperr))
1199 * SMTP listener explicitly refuses to deliver mail
1200 * coming from this address, probably due to an
1201 * anti-spam domain exclusion. Respect this. Don't
1202 * try to ship the message, and don't prevent it from
1203 * being deleted. Typical values:
1205 * 571 = sendmail's "unsolicited email refused"
1206 * 501 = exim's old antispam response
1207 * 550 = exim's new antispam response (temporary)
1209 * We don't send bouncemail on antispam failures because
1210 * we don't want the scumbags to know the address is even
1213 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1215 free_str_list(&xmit_names);
1220 * Suppress error message only if the response specifically
1221 * meant `excluded for policy reasons'. We *should* see
1222 * an error when the return code is less specific.
1225 error(0, -1, "SMTP error: %s", smtp_response);
1229 case 452: /* insufficient system storage */
1231 * Temporary out-of-queue-space condition on the
1232 * ESMTP server. Don't try to ship the message,
1233 * and suppress deletion so it can be retried on
1234 * a future retrieval cycle.
1236 * Bouncemail *might* be appropriate here as a delay
1237 * notification. But it's not really necessary because
1238 * this is not an actual failure, we're very likely to be
1239 * able to recover on the next cycle.
1241 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1243 free_str_list(&xmit_names);
1244 return(PS_TRANSIENT);
1246 case 552: /* message exceeds fixed maximum message size */
1247 case 553: /* invalid sending domain */
1249 * Permanent no-go condition on the
1250 * ESMTP server. Don't try to ship the message,
1251 * and allow it to be deleted.
1253 * Bouncemail would be appropriate for 552, but in these
1254 * latter days 553 usually means a spammer is trying to
1255 * cover his tracks. We'd rather deny the scumbags any
1256 * feedback that the address is valid.
1258 SMTP_rset(ctl->smtp_socket); /* required by RFC1870 */
1260 free_str_list(&xmit_names);
1263 default: /* retry with invoking user's address */
1264 if (SMTP_from(ctl->smtp_socket, user, options) != SM_OK)
1266 error(0, -1, "SMTP error: %s", smtp_response);
1268 free_str_list(&xmit_names);
1269 return(PS_SMTP); /* should never happen */
1275 * Now list the recipient addressees
1277 * RFC 1123 requires that the domain name part of the
1278 * RCPT TO address be "canonicalized", that is a FQDN
1279 * or MX but not a CNAME. Some listeners (like exim)
1282 destaddr = ctl->smtpaddress ? ctl->smtpaddress : ( ctl->smtphost ? ctl->smtphost : "localhost");
1284 for (idp = xmit_names; idp; idp = idp->next)
1285 if (idp->val.status.mark == XMIT_ACCEPT)
1287 if (strchr(idp->id, '@'))
1288 strcpy(addr, idp->id);
1290 #ifdef HAVE_SNPRINTF
1291 snprintf(addr, sizeof(addr)-1, "%s@%s", idp->id, destaddr);
1293 sprintf(addr, "%s@%s", idp->id, destaddr);
1294 #endif /* HAVE_SNPRINTF */
1296 if (SMTP_rcpt(ctl->smtp_socket, addr) == SM_OK)
1301 idp->val.status.mark = XMIT_ANTISPAM;
1303 "SMTP listener doesn't like recipient address `%s'",
1307 if (!good_addresses)
1309 #ifdef HAVE_SNPRINTF
1310 snprintf(addr, sizeof(addr)-1, "%s@%s", user, destaddr);
1312 sprintf(addr, "%s@%s", user, destaddr);
1313 #endif /* HAVE_SNPRINTF */
1315 if (SMTP_rcpt(ctl->smtp_socket, addr) != SM_OK)
1317 error(0, 0, "can't even send to calling user!");
1319 free_str_list(&xmit_names);
1324 /* tell it we're ready to send data */
1325 SMTP_data(ctl->smtp_socket);
1330 * Some server/sendmail combinations cause problems when our
1331 * synthetic Received line is before the From header. Cope
1334 if ((rcv = strstr(headers, "Received:")) == (char *)NULL)
1339 n = stuffline(ctl, headers);
1342 if (!run.invisible && n != -1)
1344 /* utter any per-message Received information we need here */
1345 sprintf(buf, "Received: from %s\n", ctl->server.truename);
1346 n = stuffline(ctl, buf);
1350 * We used to include ctl->remotename in this log line,
1351 * but this can be secure information that would be bad
1354 sprintf(buf, "\tby %s (fetchmail-%s %s)\n",
1358 n = stuffline(ctl, buf);
1364 if (good_addresses == 0)
1367 "for <%s@%s> (by default); ",
1370 else if (good_addresses == 1)
1372 for (idp = xmit_names; idp; idp = idp->next)
1373 if (idp->val.status.mark == XMIT_ACCEPT)
1374 break; /* only report first address */
1375 if (strchr(idp->id, '@'))
1376 sprintf(buf+1, "for <%s>", idp->id);
1378 sprintf(buf+1, "for <%s/%s>", idp->id, destaddr);
1379 sprintf(buf+strlen(buf), " (%s); ",
1380 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1386 #ifdef HAVE_STRFTIME
1388 * Conform to RFC822. This is typically going to emit
1389 * a three-letter timezone for %Z, which is going to
1390 * be marked "obsolete syntax" in 822bis. Note that we
1391 * generate a 4-digit year here.
1393 strftime(buf + strlen(buf), sizeof(buf) - strlen(buf),
1394 "%a, %d %b %Y %H:%M:%S %Z\n", localtime(&now));
1397 * This is really just a portability fallback, as the
1398 * date format ctime(3) emits is not RFC822
1401 strcat(buf, ctime(&now));
1402 #endif /* HAVE_STRFTIME */
1403 n = stuffline(ctl, buf);
1409 n = stuffline(ctl, rcv); /* ship out rest of headers */
1413 error(0, errno, "writing RFC822 headers");
1418 signal(SIGCHLD, sigchld);
1421 free_str_list(&xmit_names);
1424 else if (!run.use_syslog && outlevel == O_VERBOSE)
1427 /* write error notifications */
1428 if (no_local_matches || has_nuls || bad_addresses)
1431 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1434 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1435 if (no_local_matches)
1437 if (reject_count != 1)
1438 strcat(errhd, "no recipient addresses matched declared local names");
1441 for (idp = xmit_names; idp; idp = idp->next)
1442 if (idp->val.status.mark == XMIT_REJECT)
1444 sprintf(errhd+strlen(errhd), "recipient address %s didn't match any local name", idp->id);
1450 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1451 strcat(errhd, "; ");
1452 strcat(errhd, "message has embedded NULs");
1457 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1458 strcat(errhd, "; ");
1459 strcat(errhd, "SMTP listener rejected local recipient addresses: ");
1460 errlen = strlen(errhd);
1461 for (idp = xmit_names; idp; idp = idp->next)
1462 if (idp->val.status.mark == XMIT_ANTISPAM)
1463 errlen += strlen(idp->id) + 2;
1465 errmsg = alloca(errlen+3);
1466 (void) strcpy(errmsg, errhd);
1467 for (idp = xmit_names; idp; idp = idp->next)
1468 if (idp->val.status.mark == XMIT_ANTISPAM)
1470 strcat(errmsg, idp->id);
1472 strcat(errmsg, ", ");
1477 strcat(errmsg, "\n");
1479 /* ship out the error line */
1481 stuffline(ctl, errmsg);
1484 /* issue the delimiter line */
1489 stuffline(ctl, buf);
1492 free_str_list(&xmit_names);
1493 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1496 static int readbody(sock, ctl, forward, len)
1497 /* read and dispose of a message body presented on sock */
1498 struct query *ctl; /* query control record */
1499 int sock; /* to which the server is connected */
1500 int len; /* length of message */
1501 flag forward; /* TRUE to forward */
1504 unsigned char buf[MSGBUFSIZE+4];
1505 unsigned char *inbufp = buf;
1506 flag issoftline = FALSE;
1508 /* pass through the text lines */
1509 while (protocol->delimited || len > 0)
1511 set_timeout(ctl->server.timeout);
1512 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1519 signal(SIGCHLD, sigchld);
1525 /* write the message size dots */
1528 sizeticker += linelen;
1529 while (sizeticker >= SIZETICKER)
1531 if (!run.use_syslog && outlevel > O_SILENT)
1533 sizeticker -= SIZETICKER;
1538 /* check for end of message */
1539 if (protocol->delimited && *inbufp == '.')
1540 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1542 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1545 msglen--; /* subtract the size of the dot escape */
1549 if (ctl->mimedecode && (mimemsg & MSG_NEEDS_DECODE)) {
1550 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1551 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1554 * Soft linebreak, but less than 200 bytes left in
1555 * input buffer. Rather than doing a buffer overrun,
1556 * ignore the soft linebreak, NL-terminate data and
1557 * deliver what we have now.
1558 * (Who writes lines longer than 2K anyway?)
1560 *inbufp = '\n'; *(inbufp+1) = '\0';
1565 /* ship out the text line */
1566 if (forward && (!issoftline))
1571 /* guard against very long lines */
1572 buf[MSGBUFSIZE+1] = '\r';
1573 buf[MSGBUFSIZE+2] = '\n';
1574 buf[MSGBUFSIZE+3] = '\0';
1576 n = stuffline(ctl, buf);
1580 error(0, errno, "writing message text");
1585 signal(SIGCHLD, sigchld);
1589 else if (outlevel == O_VERBOSE)
1599 kerberos_auth (socket, canonical)
1600 /* authenticate to the server host using Kerberos V4 */
1601 int socket; /* socket to server host */
1603 char *canonical; /* server name */
1605 const char *canonical; /* server name */
1608 char * host_primary;
1612 Key_schedule schedule;
1615 ticket = ((KTEXT) (malloc (sizeof (KTEXT_ST))));
1616 rem = (krb_sendauth (0L, socket, ticket, "pop",
1618 ((char *) (krb_realmofhost (canonical))),
1619 ((unsigned long) 0),
1623 ((struct sockaddr_in *) 0),
1624 ((struct sockaddr_in *) 0),
1627 if (rem != KSUCCESS)
1629 error(0, -1, "kerberos error %s", (krb_get_err_text (rem)));
1630 return (PS_AUTHFAIL);
1634 #endif /* KERBEROS_V4 */
1638 kerberos5_auth(socket, canonical)
1639 /* authernticate to the server host using Kerberos V5 */
1640 int socket; /* socket to server host */
1641 const char *canonical; /* server name */
1643 krb5_error_code retval;
1644 krb5_context context;
1646 krb5_principal client = NULL, server = NULL;
1647 krb5_error *err_ret = NULL;
1649 krb5_auth_context auth_context = NULL;
1651 krb5_init_context(&context);
1652 krb5_init_ets(context);
1653 krb5_auth_con_init(context, &auth_context);
1655 if (retval = krb5_cc_default(context, &ccdef)) {
1656 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1660 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1661 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1665 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1668 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1672 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1673 "KPOPV1.0", client, server,
1674 AP_OPTS_MUTUAL_REQUIRED,
1675 NULL, /* no data to checksum */
1676 0, /* no creds, use ccache instead */
1680 NULL); /* don't need reply */
1682 krb5_free_principal(context, server);
1683 krb5_free_principal(context, client);
1684 krb5_auth_con_free(context, auth_context);
1687 if (err_ret && err_ret->text.length) {
1688 error(0, 0, "krb5_sendauth: %s [server says '%*s'] ",
1689 error_message(retval),
1690 err_ret->text.length,
1691 err_ret->text.data);
1692 krb5_free_error(context, err_ret);
1694 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1700 #endif /* KERBEROS_V5 */
1702 int do_protocol(ctl, proto)
1703 /* retrieve messages from server using given protocol method table */
1704 struct query *ctl; /* parsed options with merged-in defaults */
1705 const struct method *proto; /* protocol method table */
1707 int ok, js, sock = -1;
1712 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1714 error(0, -1, "Kerberos V4 support not linked.");
1717 #endif /* KERBEROS_V4 */
1720 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1722 error(0, -1, "Kerberos V5 support not linked.");
1725 #endif /* KERBEROS_V5 */
1727 /* lacking methods, there are some options that may fail */
1730 /* check for unsupported options */
1733 "Option --flush is not supported with %s",
1737 else if (ctl->fetchall) {
1739 "Option --all is not supported with %s",
1744 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1747 "Option --limit is not supported with %s",
1755 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1758 /* set up the server-nonresponse timeout */
1759 sigsave = signal(SIGALRM, timeout_handler);
1760 mytimeout = ctl->server.timeout;
1762 if ((js = setjmp(restart)) == 1)
1764 if (phase == SERVER_WAIT)
1766 "timeout after %d seconds waiting for server %s.",
1767 ctl->server.timeout, ctl->server.pollname);
1768 else if (phase == FORWARDING_WAIT)
1770 "timeout after %d seconds waiting for %s.",
1771 ctl->server.timeout,
1772 ctl->mda ? "MDA" : "SMTP");
1773 else if (phase == LISTENER_WAIT)
1775 "timeout after %d seconds waiting for listener to respond.");
1777 error(0, 0, "timeout after %d seconds.", ctl->server.timeout);
1779 if (ctl->smtp_socket != -1)
1780 close(ctl->smtp_socket);
1789 char buf [POPBUFSIZE+1], *realhost;
1790 int *msgsizes, len, num, count, new, bytes, deletions = 0;
1792 int fetches, dispatches;
1794 int port, fetches, dispatches;
1798 /* execute pre-initialization command, if any */
1799 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1801 sprintf(buf, "pre-connection command failed with status %d", ok);
1807 /* open a socket to the mail server */
1809 port = ctl->server.port ? ctl->server.port : protocol->port;
1811 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1813 if ((sock = SockOpen(realhost,
1814 ctl->server.service ? ctl->server.service : protocol->service,
1815 ctl->server.netsec)) == -1)
1817 if ((sock = SockOpen(realhost, port, NULL)) == -1)
1821 #ifndef EHOSTUNREACH
1822 #define EHOSTUNREACH (-1)
1824 if (outlevel == O_VERBOSE || errno != EHOSTUNREACH)
1826 error_build("fetchmail: %s connection to %s failed: ",
1827 protocol->name, ctl->server.pollname);
1828 #ifdef HAVE_RES_SEARCH
1829 if (h_errno == HOST_NOT_FOUND)
1830 error_complete(0, 0, "host is unknown");
1831 else if (h_errno == NO_ADDRESS)
1832 error_complete(0, 0, "name is valid but has no IP address");
1833 else if (h_errno == NO_RECOVERY)
1834 error_complete(0, 0, "unrecoverable name server error");
1835 else if (h_errno == TRY_AGAIN)
1836 error_complete(0, 0, "temporary name server error");
1838 error_complete(0, 0, "unknown DNS error %d", h_errno);
1840 #endif /* HAVE_RES_SEARCH */
1841 error_complete(0, errno, "local error");
1849 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1851 set_timeout(ctl->server.timeout);
1852 ok = kerberos_auth(sock, ctl->server.truename);
1857 #endif /* KERBEROS_V4 */
1860 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1862 set_timeout(ctl->server.timeout);
1863 ok = kerberos5_auth(sock, ctl->server.truename);
1868 #endif /* KERBEROS_V5 */
1870 /* accept greeting message from mail server */
1871 ok = (protocol->parse_response)(sock, buf);
1875 /* try to get authorized to fetch mail */
1876 if (protocol->getauth)
1878 if (protocol->password_canonify)
1879 (protocol->password_canonify)(shroud, ctl->password);
1881 strcpy(shroud, ctl->password);
1883 ok = (protocol->getauth)(sock, ctl, buf);
1886 if (ok == PS_LOCKBUSY)
1887 error(0, -1, "Lock-busy error on %s@%s",
1889 ctl->server.truename);
1894 error(0, -1, "Authorization failure on %s@%s",
1896 ctl->server.truename);
1902 ctl->errcount = fetches = 0;
1904 /* now iterate over each folder selected */
1905 for (idp = ctl->mailboxes; idp; idp = idp->next)
1912 if (outlevel >= O_VERBOSE)
1914 error(0, 0, "selecting or re-polling folder %s", idp->id);
1916 error(0, 0, "selecting or re-polling default folder");
1918 /* compute # of messages and number of new messages waiting */
1919 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1924 * We need the size of each message before it's
1925 * loaded in order to pass via the ESMTP SIZE
1926 * option. If the protocol has a getsizes method,
1927 * we presume this means it doesn't get reliable
1928 * sizes from message fetch responses.
1930 if (count > 0 && proto->getsizes)
1934 msgsizes = (int *)alloca(sizeof(int) * count);
1935 for (i = 0; i < count; i++)
1938 ok = (proto->getsizes)(sock, count, msgsizes);
1945 for (i = 0; i < count; i++)
1946 bytes += msgsizes[i];
1950 /* show user how many messages we downloaded */
1952 (void) sprintf(buf, "%s at %s (folder %s)",
1953 ctl->remotename, ctl->server.truename, idp->id);
1955 (void) sprintf(buf, "%s at %s",
1956 ctl->remotename, ctl->server.truename);
1957 if (outlevel > O_SILENT)
1958 if (count == -1) /* only used for ETRN */
1959 error(0, 0, "Polling %s", ctl->server.truename);
1960 else if (count != 0)
1962 if (new != -1 && (count - new) > 0)
1963 error_build("%d message%s (%d seen) for %s",
1964 count, count > 1 ? "s" : "", count-new, buf);
1966 error_build("%d message%s for %s",
1967 count, count > 1 ? "s" : "", buf);
1969 error_complete(0, 0, ".");
1971 error_complete(0, 0, " (%d bytes).", bytes);
1975 /* these are pointless in normal daemon mode */
1976 if (pass == 1 && (run.poll_interval == 0 || outlevel == O_VERBOSE))
1977 error(0, 0, "No mail for %s", buf);
1980 /* very important, this is where we leave the do loop */
1986 if (new == -1 || ctl->fetchall)
1988 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1993 flag force_retrieval;
1996 * What forces this code is that in POP2 and
1997 * IMAP2bis you can't fetch a message without
1998 * having it marked `seen'. In POP3 and IMAP4, on the
1999 * other hand, you can (peek_capable is set by
2000 * each driver module to convey this; it's not a
2001 * method constant because of the difference between
2002 * IMAP2bis and IMAP4).
2004 * The result of being unable to peek is that if there's
2005 * any kind of transient error (DNS lookup failure, or
2006 * sendmail refusing delivery due to process-table limits)
2007 * the message will be marked "seen" on the server without
2008 * having been delivered. This is not a big problem if
2009 * fetchmail is running in foreground, because the user
2010 * will see a "skipped" message when it next runs and get
2013 * But in daemon mode this leads to the message
2014 * being silently ignored forever. This is not
2017 * We compensate for this by checking the error
2018 * count from the previous pass and forcing all
2019 * messages to be considered new if it's nonzero.
2021 force_retrieval = !peek_capable && (ctl->errcount > 0);
2023 /* read, forward, and delete messages */
2024 for (num = 1; num <= count; num++)
2026 flag toolarge = NUM_NONZERO(ctl->limit)
2027 && msgsizes && (msgsizes[num-1] > ctl->limit);
2028 flag fetch_it = !toolarge
2029 && (ctl->fetchall || force_retrieval || !(protocol->is_old && (protocol->is_old)(sock,ctl,num)));
2030 flag suppress_delete = FALSE;
2031 flag suppress_forward = FALSE;
2032 flag suppress_readbody = FALSE;
2033 flag retained = FALSE;
2036 * This check copes with Post Office/NT's
2037 * annoying habit of randomly prepending bogus
2038 * LIST items of length -1. Patrick Audley
2039 * <paudley@pobox.com> tells us: LIST shows a
2040 * size of -1, RETR and TOP return "-ERR
2041 * System error - couldn't open message", and
2042 * DELE succeeds but doesn't actually delete
2045 if (msgsizes && msgsizes[num-1] == -1)
2047 if (outlevel >= O_VERBOSE)
2049 "Skipping message %d, length -1",
2054 /* we may want to reject this message if it's old */
2057 if (outlevel > O_SILENT)
2059 error_build("skipping message %d", num);
2061 error_build(" (oversized, %d bytes)",
2067 flag wholesize = !protocol->fetch_body;
2069 /* request a message */
2070 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
2074 /* -1 means we didn't see a size in the response */
2075 if (len == -1 && msgsizes)
2077 len = msgsizes[num - 1];
2081 if (outlevel > O_SILENT)
2083 error_build("reading message %d of %d",
2087 error_build(" (%d %sbytes)",
2088 len, wholesize ? "" : "header ");
2089 if (outlevel == O_VERBOSE)
2090 error_complete(0, 0, "");
2095 /* later we'll test for this before closing */
2096 sinkfp = (FILE *)NULL;
2099 * Read the message headers and ship them to the
2102 ok = readheaders(sock, len, msgsizes[num-1],
2104 if (ok == PS_RETAINED)
2105 suppress_forward = retained = TRUE;
2106 else if (ok == PS_TRANSIENT)
2107 suppress_delete = suppress_forward = TRUE;
2108 else if (ok == PS_REFUSED)
2109 suppress_forward = TRUE;
2110 else if (ok == PS_TRUNCATED)
2111 suppress_readbody = TRUE;
2116 * If we're using IMAP4 or something else that
2117 * can fetch headers separately from bodies,
2118 * it's time to request the body now. This
2119 * fetch may be skipped if we got an anti-spam
2120 * or other PS_REFUSED error response during
2123 if (protocol->fetch_body && !suppress_readbody)
2125 if (outlevel == O_VERBOSE)
2126 fputc('\n', stderr);
2128 if ((ok = (protocol->trail)(sock, ctl, num)))
2131 if (!suppress_forward)
2133 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
2135 if (outlevel > O_SILENT && !wholesize)
2136 error_build(" (%d body bytes) ", len);
2140 /* process the body now */
2143 if (suppress_readbody)
2145 /* When readheaders returns PS_TRUNCATED,
2146 the body (which has no content
2147 has already been read by readheaders,
2148 so we say readbody returned PS_SUCCESS */
2158 if (ok == PS_TRANSIENT)
2159 suppress_delete = suppress_forward = TRUE;
2163 /* tell server we got it OK and resynchronize */
2164 if (protocol->trail)
2166 if (outlevel == O_VERBOSE)
2167 fputc('\n', stderr);
2169 ok = (protocol->trail)(sock, ctl, num);
2175 /* count # messages forwarded on this pass */
2176 if (!suppress_forward)
2180 * Check to see if the numbers matched?
2182 * Yes, some servers foo this up horribly.
2183 * All IMAP servers seem to get it right, and
2184 * so does Eudora QPOP at least in 2.xx
2187 * Microsoft Exchange gets it completely
2188 * wrong, reporting compressed rather than
2189 * actual sizes (so the actual length of
2190 * message is longer than the reported size).
2191 * Another fine example of Microsoft brain death!
2193 * Some older POP servers, like the old UCB
2194 * POP server and the pre-QPOP QUALCOMM
2195 * versions, report a longer size in the LIST
2196 * response than actually gets shipped up.
2197 * It's unclear what is going on here, as the
2198 * QUALCOMM server (at least) seems to be
2199 * reporting the on-disk size correctly.
2201 if (msgsizes && msglen != msgsizes[num-1])
2203 if (outlevel >= O_VERBOSE)
2205 "message %d was not the expected length (%d != %d)",
2206 num, msglen, msgsizes[num-1]);
2209 /* end-of-message processing starts here */
2215 /* close the delivery pipe, we'll reopen before next message */
2217 rc = pclose(sinkfp);
2220 signal(SIGCHLD, sigchld);
2223 error(0, -1, "MDA exited abnormally or returned nonzero status");
2227 else if (!suppress_forward)
2229 /* write message terminator */
2230 if (SMTP_eom(ctl->smtp_socket) != SM_OK)
2232 error(0, -1, "SMTP listener refused delivery");
2234 suppress_delete = TRUE;
2242 * At this point in flow of control, either
2243 * we've bombed on a protocol error or had
2244 * delivery refused by the SMTP server
2245 * (unlikely -- I've never seen it) or we've
2246 * seen `accepted for delivery' and the
2247 * message is shipped. It's safe to mark the
2248 * message seen and delete it on the server
2252 /* tell the UID code we've seen this */
2257 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2258 if (sdp->val.status.num == num)
2259 sdp->val.status.mark = UID_SEEN;
2262 /* maybe we delete this message now? */
2265 if (outlevel > O_SILENT)
2266 error_complete(0, 0, " retained");
2268 else if (protocol->delete
2270 && (fetch_it ? !ctl->keep : ctl->flush))
2273 if (outlevel > O_SILENT)
2274 error_complete(0, 0, " flushed");
2275 ok = (protocol->delete)(sock, ctl, num);
2279 delete_str(&ctl->newsaved, num);
2280 #endif /* POP3_ENABLE */
2282 else if (outlevel > O_SILENT)
2283 error_complete(0, 0, " not flushed");
2285 /* perhaps this as many as we're ready to handle */
2286 if (NUM_NONZERO(ctl->fetchlimit) && ctl->fetchlimit <= fetches)
2292 * Only re-poll if we had some actual forwards, allowed
2293 * deletions and had no errors.
2294 * Otherwise it is far too easy to get into infinite loops.
2296 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2300 ok = (protocol->logout_cmd)(sock, ctl);
2302 * Hmmmm...arguably this would be incorrect if we had fetches but
2303 * no dispatches (due to oversized messages, etc.)
2306 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2311 if (ok != 0 && ok != PS_SOCKET)
2312 (protocol->logout_cmd)(sock, ctl);
2316 msg = (char *)NULL; /* sacrifice to -Wall */
2323 msg = "authorization";
2326 msg = "missing or bad RFC822 header";
2332 msg = "client/server synchronization";
2335 msg = "client/server protocol";
2338 msg = "lock busy on server";
2341 msg = "SMTP transaction";
2347 error(0, 0, "undefined");
2350 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2351 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2352 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2353 error(0,-1, "%s error while fetching from %s", msg, ctl->server.pollname);
2356 /* execute post-initialization command, if any */
2357 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2361 sprintf(buf, "post-connection command failed with status %d", ok);
2363 if (ok == PS_SUCCESS)
2367 signal(SIGALRM, sigsave);
2371 #if defined(HAVE_STDARG_H)
2372 void gen_send(int sock, const char *fmt, ... )
2373 /* assemble command in printf(3) style and send to the server */
2375 void gen_send(sock, fmt, va_alist)
2376 /* assemble command in printf(3) style and send to the server */
2377 int sock; /* socket to which server is connected */
2378 const char *fmt; /* printf-style format */
2382 char buf [MSGBUFSIZE+1];
2385 if (protocol->tagged)
2386 (void) sprintf(buf, "%s ", GENSYM);
2390 #if defined(HAVE_STDARG_H)
2395 #ifdef HAVE_VSNPRINTF
2396 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2398 vsprintf(buf + strlen(buf), fmt, ap);
2402 strcat(buf, "\r\n");
2403 SockWrite(sock, buf, strlen(buf));
2405 if (outlevel == O_VERBOSE)
2409 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2413 sp = cp + strlen(shroud);
2419 buf[strlen(buf)-2] = '\0';
2420 error(0, 0, "%s> %s", protocol->name, buf);
2424 int gen_recv(sock, buf, size)
2425 /* get one line of input from the server */
2426 int sock; /* socket to which server is connected */
2427 char *buf; /* buffer to receive input */
2428 int size; /* length of buffer */
2430 int oldphase = phase; /* we don't have to be re-entrant */
2432 phase = SERVER_WAIT;
2433 set_timeout(mytimeout);
2434 if (SockRead(sock, buf, size) == -1)
2443 if (buf[strlen(buf)-1] == '\n')
2444 buf[strlen(buf)-1] = '\0';
2445 if (buf[strlen(buf)-1] == '\r')
2446 buf[strlen(buf)-1] = '\0';
2447 if (outlevel == O_VERBOSE)
2448 error(0, 0, "%s< %s", protocol->name, buf);
2454 #if defined(HAVE_STDARG_H)
2455 int gen_transact(int sock, char *fmt, ... )
2456 /* assemble command in printf(3) style, send to server, accept a response */
2458 int gen_transact(int sock, fmt, va_alist)
2459 /* assemble command in printf(3) style, send to server, accept a response */
2460 int sock; /* socket to which server is connected */
2461 const char *fmt; /* printf-style format */
2466 char buf [MSGBUFSIZE+1];
2468 int oldphase = phase; /* we don't have to be re-entrant */
2470 phase = SERVER_WAIT;
2472 if (protocol->tagged)
2473 (void) sprintf(buf, "%s ", GENSYM);
2477 #if defined(HAVE_STDARG_H)
2482 #ifdef HAVE_VSNPRINTF
2483 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2485 vsprintf(buf + strlen(buf), fmt, ap);
2489 strcat(buf, "\r\n");
2490 SockWrite(sock, buf, strlen(buf));
2492 if (outlevel == O_VERBOSE)
2496 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2500 sp = cp + strlen(shroud);
2506 buf[strlen(buf)-1] = '\0';
2507 error(0, 0, "%s> %s", protocol->name, buf);
2510 /* we presume this does its own response echoing */
2511 ok = (protocol->parse_response)(sock, buf);
2517 /* driver.c ends here */