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_SYS_ITIMER_H)
29 #include <sys/itimer.h>
34 #ifdef HAVE_NET_SOCKET_H
35 #include <net/socket.h>
38 #ifdef HAVE_RES_SEARCH
41 #endif /* HAVE_RES_SEARCH */
45 #include <kerberosIV/des.h>
46 #include <kerberosIV/krb.h>
48 #if defined (__bsdi__)
49 #include <des.h> /* order of includes matters */
51 #define krb_get_err_text(e) (krb_err_txt[e])
53 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
54 #define krb_get_err_text(e) (krb_err_txt[e])
60 #endif /* ! defined (__FreeBSD__) */
61 #endif /* ! defined (__bsdi__) */
62 #endif /* KERBEROS_V5 */
63 #include <netinet/in.h>
65 #endif /* KERBEROS_V4 */
69 #endif /* KERBEROS_V5 */
73 #include "fetchmail.h"
76 /* throw types for runtime errors */
77 #define THROW_TIMEOUT 1 /* server timed out */
78 #define THROW_SIGPIPE 2 /* SIGPIPE on stream socket */
80 #ifndef strstr /* glibc-2.1 declares this as a macro */
81 extern char *strstr(); /* needed on sysV68 R3V7.1. */
84 int batchcount; /* count of messages sent in current batch */
85 flag peek_capable; /* can we peek for better error recovery? */
86 int pass; /* how many times have we re-polled? */
87 int stage; /* where are we? */
88 int phase; /* where are we, for error-logging purposes? */
89 int mytimeout; /* value of nonreponse timeout */
91 static const struct method *protocol;
92 static jmp_buf restart;
96 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
98 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
99 static int timeoutcount; /* count consecutive timeouts */
100 static int msglen; /* actual message length */
102 void set_timeout(int timeleft)
103 /* reset the nonresponse-timeout */
105 #if !defined(__EMX__) && !defined(__BEOS__)
106 struct itimerval ntimeout;
111 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
112 ntimeout.it_value.tv_sec = timeleft;
113 ntimeout.it_value.tv_usec = 0;
114 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
118 static void timeout_handler (int signal)
119 /* handle SIGALRM signal indicating a server timeout */
122 longjmp(restart, THROW_TIMEOUT);
125 static void sigpipe_handler (int signal)
126 /* handle SIGPIPE signal indicating a broken stream socket */
128 longjmp(restart, THROW_SIGPIPE);
131 static int accept_count, reject_count;
133 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
134 /* add given name to xmit_names if it matches declared localnames */
135 /* name: name to map */
136 /* ctl: list of permissible aliases */
137 /* xmit_names: list of recipient names parsed out */
142 lname = idpair_find(&ctl->localnames, name+off);
143 if (!lname && ctl->wildcard)
146 if (lname != (char *)NULL)
148 if (outlevel >= O_DEBUG)
149 report(stdout, _("mapped %s to local %s\n"), name, lname);
150 save_str(xmit_names, lname, XMIT_ACCEPT);
155 static void find_server_names(const char *hdr,
157 struct idlist **xmit_names)
158 /* parse names out of a RFC822 header into an ID list */
159 /* hdr: RFC822 header in question */
160 /* ctl: list of permissible aliases */
161 /* xmit_names: list of recipient names parsed out */
163 if (hdr == (char *)NULL)
169 for (cp = nxtaddr(hdr);
176 * If the name of the user begins with a qmail virtual
177 * domain prefix, ignore the prefix. Doing this here
178 * means qvirtual will work either with ordinary name
179 * mapping or with a localdomains option.
181 if (ctl->server.qvirtual)
183 int sl = strlen(ctl->server.qvirtual);
185 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
189 if ((atsign = strchr(cp, '@'))) {
193 * Does a trailing segment of the hostname match something
194 * on the localdomains list? If so, save the whole name
197 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
200 rhs = atsign + (strlen(atsign) - strlen(idp->id));
202 (rhs[-1] == '.' || rhs[-1] == '@') &&
203 strcasecmp(rhs, idp->id) == 0)
205 if (outlevel >= O_DEBUG)
206 report(stdout, _("passed through %s matching %s\n"),
208 save_str(xmit_names, cp, XMIT_ACCEPT);
214 /* if we matched a local domain, idp != NULL */
218 * Check to see if the right-hand part is an alias
219 * or MX equivalent of the mailserver. If it's
220 * not, skip this name. If it is, we'll keep
221 * going and try to find a mapping to a client name.
223 if (!is_host_alias(atsign+1, ctl))
225 save_str(xmit_names, cp, XMIT_REJECT);
231 map_name(cp, ctl, xmit_names);
239 * Return zero on a syntactically invalid address, nz on a valid one.
241 * This used to be strchr(a, '.'), but it turns out that lines like this
243 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
244 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
246 * are not uncommon. So now we just check that the following token is
247 * not itself an email address.
249 #define VALID_ADDRESS(a) !strchr(a, '@')
251 static char *parse_received(struct query *ctl, char *bufp)
252 /* try to extract real address from the Received line */
253 /* If a valid Received: line is found, we return the full address in
254 * a buffer which can be parsed from nxtaddr(). This is to ansure that
255 * the local domain part of the address can be passed along in
256 * find_server_names() if it contains one.
257 * Note: We should return a dummy header containing the address
258 * which makes nxtaddr() behave correctly.
261 char *base, *ok = (char *)NULL;
262 static char rbuf[HOSTLEN + USERNAMELEN + 4];
265 * Try to extract the real envelope addressee. We look here
266 * specifically for the mailserver's Received line.
267 * Note: this will only work for sendmail, or an MTA that
268 * shares sendmail's convention for embedding the envelope
269 * address in the Received line. Sendmail itself only
270 * does this when the mail has a single recipient.
272 if (outlevel >= O_DEBUG)
273 report(stdout, _("analyzing Received line:\n%s"), bufp);
275 /* search for whitepace-surrounded "by" followed by valid address */
276 for (base = bufp; ; base = ok + 2)
278 if (!(ok = strstr(base, "by")))
280 else if (!isspace(ok[-1]) || !isspace(ok[2]))
286 /* extract space-delimited token after "by" */
287 for (sp = ok + 2; isspace(*sp); sp++)
290 for (; !isspace(*sp); sp++)
294 /* look for valid address */
295 if (VALID_ADDRESS(rbuf))
298 ok = sp - 1; /* arrange to skip this token */
304 * If it's a DNS name of the mail server, look for the
305 * recipient name after a following "for". Otherwise
308 if (is_host_alias(rbuf, ctl))
310 if (outlevel >= O_DEBUG)
312 _("line accepted, %s is an alias of the mailserver\n"), rbuf);
316 if (outlevel >= O_DEBUG)
318 _("line rejected, %s is not an alias of the mailserver\n"),
323 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
324 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
326 if (!(ok = strstr(base, "for")))
328 else if (!isspace(ok[-1]) || !isspace(ok[3]))
334 /* extract space-delimited token after "for" */
335 for (sp = ok + 3; isspace(*sp); sp++)
338 for (; !isspace(*sp); sp++)
342 if (strchr(rbuf, '@'))
345 ok = sp - 1; /* arrange to skip this token */
350 flag want_gt = FALSE;
353 /* char after "for" could be space or a continuation newline */
354 for (sp = ok + 4; isspace(*sp); sp++)
357 *tp++ = ':'; /* Here is the hack. This is to be friends */
358 *tp++ = ' '; /* with nxtaddr()... */
364 while (*sp == '@') /* skip routes */
365 while (*sp && *sp++ != ':')
368 && (want_gt ? (*sp != '>') : !isspace(*sp))
374 /* uh oh -- whitespace here can't be right! */
380 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
388 if (outlevel >= O_DEBUG)
389 report(stdout, _("no Received address found\n"));
394 if (outlevel >= O_DEBUG) {
395 char *lf = rbuf + strlen(rbuf)-1;
397 if (outlevel >= O_DEBUG)
398 report(stdout, _("found Received address `%s'\n"), rbuf+2);
405 /* shared by readheaders and readbody */
406 static int sizeticker;
407 static struct msgblk msgblk;
409 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
411 static int readheaders(int sock,
416 /* read message headers and ship to SMTP or MDA */
417 /* sock: to which the server is connected */
418 /* fetchlen: length of message according to fetch response */
419 /* reallen: length of message according to getsizes */
420 /* ctl: query control record */
421 /* num: index of message */
426 struct addrblk *next;
428 struct addrblk *to_addrchain = NULL;
429 struct addrblk **to_chainptr = &to_addrchain;
430 struct addrblk *resent_to_addrchain = NULL;
431 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
433 char buf[MSGBUFSIZE+1];
434 int from_offs, reply_to_offs, resent_from_offs;
435 int app_from_offs, sender_offs, resent_sender_offs;
437 char *received_for, *rcv, *cp;
438 int n, linelen, oldlen, ch, remaining, skipcount;
440 flag no_local_matches = FALSE;
441 flag headers_ok, has_nuls;
442 int olderrs, good_addresses, bad_addresses;
445 has_nuls = headers_ok = FALSE;
446 msgblk.return_path[0] = '\0';
447 olderrs = ctl->errcount;
449 /* read message headers */
450 msgblk.reallen = reallen;
451 msgblk.headers = received_for = NULL;
452 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
453 sender_offs = resent_sender_offs = env_offs = -1;
459 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
463 line = xmalloc(sizeof(buf));
467 set_timeout(mytimeout);
468 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
471 free(msgblk.headers);
478 /* lines may not be properly CRLF terminated; fix this for qmail */
481 cp = buf + strlen(buf) - 1;
482 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
491 * Decode MIME encoded headers. We MUST do this before
492 * looking at the Content-Type / Content-Transfer-Encoding
493 * headers (RFC 2046).
498 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
502 /* check for end of headers */
506 has_nuls = (linelen != strlen(line));
508 goto process_headers;
512 * Check for end of message immediately. If one of your folders
513 * has been mangled, the delimiter may occur directly after the
516 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
519 has_nuls = (linelen != strlen(line));
520 goto process_headers;
523 /* check for RFC822 continuations */
524 set_timeout(mytimeout);
528 (ch == ' ' || ch == '\t'); /* continuation to next line? */
530 /* write the message size dots */
531 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
533 sizeticker += linelen;
534 while (sizeticker >= SIZETICKER)
536 if (!run.use_syslog && isatty(1))
541 sizeticker -= SIZETICKER;
545 /* we see an ordinary (non-header, non-message-delimiter line */
546 has_nuls = (linelen != strlen(line));
549 * When mail delivered to a multidrop mailbox on the server is
550 * addressed to multiple people on the client machine, there
551 * will be one copy left in the box for each recipient. Thus,
552 * if the mail is addressed to N people, each recipient will
555 * Foil this by suppressing all but one copy of a message with
556 * a given Message-ID. Note: This implementation only catches
557 * runs of successive identical messages, but that should be
560 * The accept_count test ensures that multiple pieces of identical
561 * email, each with a *single* addressee, won't be suppressed.
563 if (MULTIDROP(ctl) && accept_count > 1 && !strncasecmp(line, "Message-ID:", 11))
565 if (ctl->lastid && !strcasecmp(ctl->lastid, line))
571 ctl->lastid = strdup(line);
576 * The University of Washington IMAP server (the reference
577 * implementation of IMAP4 written by Mark Crispin) relies
578 * on being able to keep base-UID information in a special
579 * message at the head of the mailbox. This message should
580 * neither be deleted nor forwarded.
584 * We disable this check under POP2 because there's no way to
585 * prevent deletion of the message. So at least we ought to
586 * forward it to the user so he or she will have some clue
587 * that things have gone awry.
590 if (strncmp(protocol->service, "pop2", 4))
591 #else /* INET6_ENABLE */
592 if (protocol->port != 109)
593 #endif /* INET6_ENABLE */
594 #endif /* POP2_ENABLE */
595 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
597 free(msgblk.headers);
602 * This code prevents fetchmail from becoming an accessory after
603 * the fact to upstream sendmails with the `E' option on. It also
604 * copes with certain brain-dead POP servers (like NT's) that pass
605 * through Unix from_ lines.
607 * Either of these bugs can result in a non-RFC822 line at the
608 * beginning of the headers. If fetchmail just passes it
609 * through, the client listener may think the message has *no*
610 * headers (since the first) line it sees doesn't look
611 * RFC822-conformant) and fake up a set.
613 * What the user would see in this case is bogus (synthesized)
614 * headers, followed by a blank line, followed by the >From,
615 * followed by the real headers, followed by a blank line,
618 * We forestall this lossage by tossing anything that looks
619 * like an escaped or passed-through From_ line in headers.
620 * These aren't RFC822 so our conscience is clear...
622 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
629 * If we see a Status line, it may have been inserted by an MUA
630 * on the mail host, or it may have been inserted by the server
631 * program after the headers in the transaction stream. This
632 * can actually hose some new-mail notifiers such as xbuffy,
633 * which assumes any Status line came from a *local* MDA and
634 * therefore indicates that the message has been seen.
636 * Some buggy POP servers (including at least the 3.3(20)
637 * version of the one distributed with IMAP) insert empty
638 * Status lines in the transaction stream; we'll chuck those
639 * unconditionally. Nonempty ones get chucked if the user
640 * turns on the dropstatus flag.
645 if (!strncasecmp(line, "Status:", 7))
647 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
652 while (*cp && isspace(*cp)) cp++;
653 if (!*cp || ctl->dropstatus)
662 line = reply_hack(line, ctl->server.truename);
665 * OK, this is messy. If we're forwarding by SMTP, it's the
666 * SMTP-receiver's job (according to RFC821, page 22, section
667 * 4.1.1) to generate a Return-Path line on final delivery.
668 * The trouble is, we've already got one because the
669 * mailserver's SMTP thought *it* was responsible for final
672 * Stash away the contents of Return-Path (as modified by reply_hack)
673 * for use in generating MAIL FROM later on, then prevent the header
674 * from being saved with the others. In effect, we strip it off here.
676 * If the SMTP server conforms to the standards, and fetchmail gets the
677 * envelope sender from the Return-Path, the new Return-Path should be
678 * exactly the same as the original one.
680 * We do *not* want to ignore empty Return-Path headers. These should
681 * be passed through as a way of indicating that a message should
682 * not trigger bounces if delivery fails. What we *do* need to do is
683 * make sure we never try to rewrite such a blank Return-Path. We
684 * handle this with a check for <> in the rewrite logic above.
686 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
688 strcpy(msgblk.return_path, cp);
697 oldlen = strlen(line);
698 msgblk.headers = xmalloc(oldlen + 1);
699 (void) strcpy(msgblk.headers, line);
701 line = msgblk.headers;
707 newlen = oldlen + strlen(line);
708 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
709 if (msgblk.headers == NULL) {
713 strcpy(msgblk.headers + oldlen, line);
715 line = msgblk.headers + oldlen;
719 if (!strncasecmp("From:", line, 5))
720 from_offs = (line - msgblk.headers);
721 else if (!strncasecmp("Reply-To:", line, 9))
722 reply_to_offs = (line - msgblk.headers);
723 else if (!strncasecmp("Resent-From:", line, 12))
724 resent_from_offs = (line - msgblk.headers);
725 else if (!strncasecmp("Apparently-From:", line, 16))
726 app_from_offs = (line - msgblk.headers);
727 else if (!strncasecmp("Sender:", line, 7))
728 sender_offs = (line - msgblk.headers);
729 else if (!strncasecmp("Resent-Sender:", line, 14))
730 resent_sender_offs = (line - msgblk.headers);
733 else if (!strncasecmp("Message-Id:", line, 11))
735 if (ctl->server.uidl)
739 line[IDLEN+12] = 0; /* prevent stack overflow */
740 sscanf(line+12, "%s", id);
741 if (!str_find( &ctl->newsaved, num))
743 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
744 new->val.status.num = num;
748 #endif /* __UNUSED__ */
750 else if (!MULTIDROP(ctl))
753 else if (!strncasecmp("To:", line, 3)
754 || !strncasecmp("Cc:", line, 3)
755 || !strncasecmp("Bcc:", line, 4)
756 || !strncasecmp("Apparently-To:", line, 14))
758 *to_chainptr = xmalloc(sizeof(struct addrblk));
759 (*to_chainptr)->offset = (line - msgblk.headers);
760 to_chainptr = &(*to_chainptr)->next;
764 else if (!strncasecmp("Resent-To:", line, 10)
765 || !strncasecmp("Resent-Cc:", line, 10)
766 || !strncasecmp("Resent-Bcc:", line, 11))
768 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
769 (*resent_to_chainptr)->offset = (line - msgblk.headers);
770 resent_to_chainptr = &(*resent_to_chainptr)->next;
771 *resent_to_chainptr = NULL;
774 else if (ctl->server.envelope != STRING_DISABLED)
776 if (ctl->server.envelope
777 && strcasecmp(ctl->server.envelope, "Received"))
779 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
781 strlen(ctl->server.envelope)))
783 if (skipcount++ != ctl->server.envskip)
785 env_offs = (line - msgblk.headers);
788 else if (!received_for && !strncasecmp("Received:", line, 9))
790 if (skipcount++ != ctl->server.envskip)
792 received_for = parse_received(ctl, line);
799 * We want to detect this early in case there are so few headers that the
800 * dispatch logic barfs.
804 if (outlevel > O_SILENT)
806 _("message delimiter found while scanning headers\n"));
810 * Hack time. If the first line of the message was blank, with no headers
811 * (this happens occasionally due to bad gatewaying software) cons up
812 * a set of fake headers.
814 * If you modify the fake header template below, be sure you don't
815 * make either From or To address @-less, otherwise the reply_hack
816 * logic will do bad things.
818 if (msgblk.headers == (char *)NULL)
821 snprintf(buf, sizeof(buf),
824 #endif /* HAVE_SNPRINTF */
825 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
826 user, fetchmailhost, ctl->remotename, ctl->server.truename);
827 msgblk.headers = xstrdup(buf);
831 * We can now process message headers before reading the text.
832 * In fact we have to, as this will tell us where to forward to.
835 /* Check for MIME headers indicating possible 8-bit data */
836 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
839 if (ctl->server.sdps && sdps_envfrom)
841 /* We have the real envelope return-path, stored out of band by
842 * SDPS - that's more accurate than any header is going to be.
844 strcpy(msgblk.return_path, sdps_envfrom);
847 #endif /* SDPS_ENABLE */
849 * If there is a Return-Path address on the message, this was
850 * almost certainly the MAIL FROM address given the originating
851 * sendmail. This is the best thing to use for logging the
852 * message origin (it sets up the right behavior for bounces and
853 * mailing lists). Otherwise, fall down to the next available
854 * envelope address (which is the most probable real sender).
855 * *** The order is important! ***
856 * This is especially useful when receiving mailing list
857 * messages in multidrop mode. if a local address doesn't
858 * exist, the bounce message won't be returned blindly to the
859 * author or to the list itself but rather to the list manager
860 * (ex: specified by "Sender:") which is much less annoying. This
861 * is true for most mailing list packages.
863 if( !msgblk.return_path[0] ){
865 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
866 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
867 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
868 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
869 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
870 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
871 if (ap) strcpy( msgblk.return_path, ap );
874 /* cons up a list of local recipients */
875 msgblk.recipients = (struct idlist *)NULL;
876 accept_count = reject_count = 0;
877 /* is this a multidrop box? */
881 if (ctl->server.sdps && sdps_envto)
883 /* We have the real envelope recipient, stored out of band by
884 * SDPS - that's more accurate than any header is going to be.
886 find_server_names(sdps_envto, ctl, &msgblk.recipients);
889 #endif /* SDPS_ENABLE */
890 if (env_offs > -1) /* We have the actual envelope addressee */
891 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
892 else if (received_for)
894 * We have the Received for addressee.
895 * It has to be a mailserver address, or we
896 * wouldn't have got here.
897 * We use find_server_names() to let local
898 * hostnames go through.
900 find_server_names(received_for, ctl, &msgblk.recipients);
904 * We haven't extracted the envelope address.
905 * So check all the "Resent-To" header addresses if
906 * they exist. If and only if they don't, consider
907 * the "To" addresses.
909 register struct addrblk *nextptr;
910 if (resent_to_addrchain) {
911 /* delete the "To" chain and substitute it
912 * with the "Resent-To" list
914 while (to_addrchain) {
915 nextptr = to_addrchain->next;
917 to_addrchain = nextptr;
919 to_addrchain = resent_to_addrchain;
920 resent_to_addrchain = NULL;
922 /* now look for remaining adresses */
923 while (to_addrchain) {
924 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
925 nextptr = to_addrchain->next;
927 to_addrchain = nextptr;
932 no_local_matches = TRUE;
933 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
934 if (outlevel >= O_DEBUG)
936 _("no local matches, forwarding to %s\n"),
940 else /* it's a single-drop box, use first localname */
941 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
945 * Time to either address the message or decide we can't deliver it yet.
947 if (ctl->errcount > olderrs) /* there were DNS errors above */
949 if (outlevel >= O_DEBUG)
951 _("forwarding and deletion suppressed due to DNS errors\n"));
952 free(msgblk.headers);
953 free_str_list(&msgblk.recipients);
954 return(PS_TRANSIENT);
958 /* set up stuffline() so we can deliver the message body through it */
959 if ((n = open_sink(ctl, &msgblk,
960 &good_addresses, &bad_addresses)) != PS_SUCCESS)
962 free(msgblk.headers);
963 free_str_list(&msgblk.recipients);
970 * Some server/sendmail combinations cause problems when our
971 * synthetic Received line is before the From header. Cope
974 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
975 rcv = msgblk.headers;
976 /* handle ">Received:" lines too */
977 while (rcv > msgblk.headers && rcv[-1] != '\n')
979 if (rcv > msgblk.headers)
984 n = stuffline(ctl, msgblk.headers);
987 if (!run.invisible && n != -1)
989 /* utter any per-message Received information we need here */
990 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
991 n = stuffline(ctl, buf);
995 * This header is technically invalid under RFC822.
996 * POP3, IMAP, etc. are not legal mail-parameter values.
998 * We used to include ctl->remotename in this log line,
999 * but this can be secure information that would be bad
1002 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
1006 n = stuffline(ctl, buf);
1010 if (good_addresses == 0)
1013 "for %s@%s (by default); ",
1014 user, ctl->destaddr);
1016 else if (good_addresses == 1)
1018 for (idp = msgblk.recipients; idp; idp = idp->next)
1019 if (idp->val.status.mark == XMIT_ACCEPT)
1020 break; /* only report first address */
1021 if (strchr(idp->id, '@'))
1022 sprintf(buf+1, "for %s", idp->id);
1025 * This could be a bit misleading, as destaddr is
1026 * the forwarding host rather than the actual
1027 * destination. Most of the time they coincide.
1029 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
1030 sprintf(buf+strlen(buf), " (%s); ",
1031 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1036 strcat(buf, rfc822timestamp());
1037 strcat(buf, "\r\n");
1038 n = stuffline(ctl, buf);
1044 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1048 report(stdout, _("writing RFC822 msgblk.headers\n"));
1050 free(msgblk.headers);
1051 free_str_list(&msgblk.recipients);
1054 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && isatty(2))
1057 /* write error notifications */
1058 if (no_local_matches || has_nuls || bad_addresses)
1061 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1064 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1065 if (no_local_matches)
1067 if (reject_count != 1)
1068 strcat(errhd, _("no recipient addresses matched declared local names"));
1071 for (idp = msgblk.recipients; idp; idp = idp->next)
1072 if (idp->val.status.mark == XMIT_REJECT)
1074 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1080 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1081 strcat(errhd, "; ");
1082 strcat(errhd, _("message has embedded NULs"));
1087 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1088 strcat(errhd, "; ");
1089 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1090 errlen = strlen(errhd);
1091 for (idp = msgblk.recipients; idp; idp = idp->next)
1092 if (idp->val.status.mark == XMIT_RCPTBAD)
1093 errlen += strlen(idp->id) + 2;
1095 xalloca(errmsg, char *, errlen+3);
1096 (void) strcpy(errmsg, errhd);
1097 for (idp = msgblk.recipients; idp; idp = idp->next)
1098 if (idp->val.status.mark == XMIT_RCPTBAD)
1100 strcat(errmsg, idp->id);
1102 strcat(errmsg, ", ");
1107 strcat(errmsg, "\r\n");
1109 /* ship out the error line */
1110 stuffline(ctl, errmsg);
1113 /* issue the delimiter line */
1118 stuffline(ctl, buf);
1120 free(msgblk.headers);
1121 free_str_list(&msgblk.recipients);
1122 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1125 static int readbody(int sock, struct query *ctl, flag forward, int len)
1126 /* read and dispose of a message body presented on sock */
1127 /* ctl: query control record */
1128 /* sock: to which the server is connected */
1129 /* len: length of message */
1130 /* forward: TRUE to forward */
1133 unsigned char buf[MSGBUFSIZE+4];
1134 unsigned char *inbufp = buf;
1135 flag issoftline = FALSE;
1138 * Pass through the text lines in the body.
1140 * Yes, this wants to be ||, not &&. The problem is that in the most
1141 * important delimited protocol, POP3, the length is not reliable.
1142 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1143 * So, for delimited protocols we need to ignore the length here and
1144 * instead drop out of the loop with a break statement when we see
1145 * the message delimiter.
1147 while (protocol->delimited || len > 0)
1149 set_timeout(mytimeout);
1150 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1158 /* write the message size dots */
1161 sizeticker += linelen;
1162 while (sizeticker >= SIZETICKER)
1164 if ((run.poll_interval == 0 || nodetach) && outlevel > O_SILENT && isatty(1))
1169 sizeticker -= SIZETICKER;
1174 /* check for end of message */
1175 if (protocol->delimited && *inbufp == '.')
1177 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1179 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1182 msglen--; /* subtract the size of the dot escape */
1187 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1188 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1189 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1192 * Soft linebreak, but less than 200 bytes left in
1193 * input buffer. Rather than doing a buffer overrun,
1194 * ignore the soft linebreak, NL-terminate data and
1195 * deliver what we have now.
1196 * (Who writes lines longer than 2K anyway?)
1198 *inbufp = '\n'; *(inbufp+1) = '\0';
1203 /* ship out the text line */
1204 if (forward && (!issoftline))
1209 /* guard against very long lines */
1210 buf[MSGBUFSIZE+1] = '\r';
1211 buf[MSGBUFSIZE+2] = '\n';
1212 buf[MSGBUFSIZE+3] = '\0';
1214 n = stuffline(ctl, buf);
1218 report(stdout, _("writing message text\n"));
1222 else if (outlevel >= O_VERBOSE && isatty(1))
1235 kerberos_auth (socket, canonical)
1236 /* authenticate to the server host using Kerberos V4 */
1237 int socket; /* socket to server host */
1238 #if defined(__FreeBSD__) || defined(__OpenBSD__)
1239 char *canonical; /* server name */
1241 const char *canonical; /* server name */
1244 char * host_primary;
1248 Key_schedule schedule;
1251 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1252 rem = (krb_sendauth (0L, socket, ticket, "pop",
1254 ((char *) (krb_realmofhost (canonical))),
1255 ((unsigned long) 0),
1259 ((struct sockaddr_in *) 0),
1260 ((struct sockaddr_in *) 0),
1262 if (rem != KSUCCESS)
1264 report(stderr, _("kerberos error %s\n"), (krb_get_err_text (rem)));
1265 return (PS_AUTHFAIL);
1269 #endif /* KERBEROS_V4 */
1272 static int kerberos5_auth(socket, canonical)
1273 /* authenticate to the server host using Kerberos V5 */
1274 int socket; /* socket to server host */
1275 const char *canonical; /* server name */
1277 krb5_error_code retval;
1278 krb5_context context;
1280 krb5_principal client = NULL, server = NULL;
1281 krb5_error *err_ret = NULL;
1283 krb5_auth_context auth_context = NULL;
1285 krb5_init_context(&context);
1286 krb5_init_ets(context);
1287 krb5_auth_con_init(context, &auth_context);
1289 if (retval = krb5_cc_default(context, &ccdef)) {
1290 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
1294 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1295 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
1299 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1302 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
1306 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1307 "KPOPV1.0", client, server,
1308 AP_OPTS_MUTUAL_REQUIRED,
1309 NULL, /* no data to checksum */
1310 0, /* no creds, use ccache instead */
1314 NULL); /* don't need reply */
1316 krb5_free_principal(context, server);
1317 krb5_free_principal(context, client);
1318 krb5_auth_con_free(context, auth_context);
1322 if (err_ret && err_ret->e_text) {
1323 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1324 error_message(retval),
1327 if (err_ret && err_ret->text.length) {
1328 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1329 error_message(retval),
1330 err_ret->text.length,
1331 err_ret->text.data);
1333 krb5_free_error(context, err_ret);
1335 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
1341 #endif /* KERBEROS_V5 */
1343 static void clean_skipped_list(struct idlist **skipped_list)
1344 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1346 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1347 prev = current = head = *skipped_list;
1353 /* if item has no reference, remove it */
1354 if (current && current->val.status.mark == 0)
1356 if (current == head) /* remove first item (head) */
1358 head = current->next;
1359 if (current->id) free(current->id);
1361 prev = current = head;
1363 else /* remove middle/last item */
1365 tmp = current->next;
1367 if (current->id) free(current->id);
1372 else /* skip this item */
1375 current = current->next;
1379 *skipped_list = head;
1382 static void send_size_warnings(struct query *ctl)
1383 /* send warning mail with skipped msg; reset msg count when user notified */
1386 int msg_to_send = FALSE;
1387 struct idlist *head=NULL, *current=NULL;
1388 int max_warning_poll_count;
1389 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server %s:"
1391 head = ctl->skipped;
1395 /* don't start a notification message unless we need to */
1396 for (current = head; current; current = current->next)
1397 if (current->val.status.num == 0 && current->val.status.mark)
1403 * There's no good way to recover if we can't send notification mail,
1404 * but it's not a disaster, either, since the skipped mail will not
1407 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1409 stuff_warning(ctl, OVERHD, ctl->server.pollname);
1411 if (run.poll_interval == 0)
1412 max_warning_poll_count = 0;
1414 max_warning_poll_count = ctl->warnings/run.poll_interval;
1416 /* parse list of skipped msg, adding items to the mail */
1417 for (current = head; current; current = current->next)
1419 if (current->val.status.num == 0 && current->val.status.mark)
1421 nbr = current->val.status.mark;
1422 size = atoi(current->id);
1424 _("\t%d msg %d octets long skipped by fetchmail.\r\n"),
1427 current->val.status.num++;
1428 current->val.status.mark = 0;
1430 if (current->val.status.num >= max_warning_poll_count)
1431 current->val.status.num = 0;
1434 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1438 static int do_session(ctl, proto, maxfetch)
1439 /* retrieve messages from server using given protocol method table */
1440 struct query *ctl; /* parsed options with merged-in defaults */
1441 const struct method *proto; /* protocol method table */
1442 const int maxfetch; /* maximum number of messages to fetch */
1445 #ifdef HAVE_VOLATILE
1446 volatile int ok, mailserver_socket = -1; /* pacifies -Wall */
1448 int ok, mailserver_socket = -1;
1449 #endif /* HAVE_VOLATILE */
1451 void (*pipesave)(int);
1452 void (*alrmsave)(int);
1453 struct idlist *current=NULL, *tmp=NULL;
1456 ctl->server.base_protocol = protocol;
1460 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1463 /* set up the server-nonresponse timeout */
1464 alrmsave = signal(SIGALRM, timeout_handler);
1465 mytimeout = ctl->server.timeout;
1467 /* set up the broken-pipe timeout */
1468 pipesave = signal(SIGPIPE, sigpipe_handler);
1470 if ((js = setjmp(restart)))
1472 #ifdef HAVE_SIGPROCMASK
1474 * Don't rely on setjmp() to restore the blocked-signal mask.
1475 * It does this under BSD but is required not to under POSIX.
1477 * If your Unix doesn't have sigprocmask, better hope it has
1478 * BSD-like behavior. Otherwise you may see fetchmail get
1479 * permanently wedged after a second timeout on a bad read,
1480 * because alarm signals were blocked after the first.
1484 sigfillset(&allsigs);
1485 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1486 #endif /* HAVE_SIGPROCMASK */
1488 if (js == THROW_SIGPIPE)
1491 _("SIGPIPE thrown from an MDA or a stream socket error\n"));
1495 else if (js == THROW_TIMEOUT)
1497 if (phase == OPEN_WAIT)
1499 _("timeout after %d seconds waiting to connect to server %s.\n"),
1500 ctl->server.timeout, ctl->server.pollname);
1501 else if (phase == SERVER_WAIT)
1503 _("timeout after %d seconds waiting for server %s.\n"),
1504 ctl->server.timeout, ctl->server.pollname);
1505 else if (phase == FORWARDING_WAIT)
1507 _("timeout after %d seconds waiting for %s.\n"),
1508 ctl->server.timeout,
1509 ctl->mda ? "MDA" : "SMTP");
1510 else if (phase == LISTENER_WAIT)
1512 _("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
1515 _("timeout after %d seconds.\n"), ctl->server.timeout);
1518 * If we've exceeded our threshold for consecutive timeouts,
1519 * try to notify the user, then mark the connection wedged.
1520 * Don't do this if the connection can idle, though; idle
1521 * timeouts just mean the frequency of mail is low.
1523 if (timeoutcount > MAX_TIMEOUTS
1524 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1527 _("Subject: fetchmail sees repeated timeouts\r\n"));
1529 _("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\r\n"),
1532 ctl->server.truename);
1534 _("This could mean that your mailserver is stuck, or that your SMTP\r\n" \
1535 "server is wedged, or that your mailbox file on the server has been\r\n" \
1536 "corrupted by a server error. You can run `fetchmail -v -v' to\r\n" \
1537 "diagnose the problem.\r\n\r\n" \
1538 "Fetchmail won't poll this mailbox again until you restart it.\r\n"));
1539 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1546 /* try to clean up all streams */
1548 if (ctl->smtp_socket != -1)
1549 SockClose(ctl->smtp_socket);
1550 if (mailserver_socket != -1)
1551 SockClose(mailserver_socket);
1555 char buf[MSGBUFSIZE+1], *realhost;
1556 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1558 int fetches, dispatches, oldphase;
1559 #else /* INET6_ENABLE */
1560 int port, fetches, dispatches, oldphase;
1561 #endif /* INET6_ENABLE */
1564 /* execute pre-initialization command, if any */
1565 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1568 _("pre-connection command failed with status %d\n"), ok);
1573 /* open a socket to the mail server */
1576 set_timeout(mytimeout);
1579 port = ctl->server.port ? ctl->server.port : ( ctl->use_ssl ? protocol->sslport : protocol->port );
1581 port = ctl->server.port ? ctl->server.port : protocol->port;
1583 #endif /* !INET6_ENABLE */
1584 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1586 /* allow time for the port to be set up if we have a plugin */
1587 if (ctl->server.plugin)
1590 if ((mailserver_socket = SockOpen(realhost,
1591 ctl->server.service ? ctl->server.service : protocol->service,
1592 ctl->server.netsec, ctl->server.plugin)) == -1)
1593 #else /* INET6_ENABLE */
1594 if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1595 #endif /* INET6_ENABLE */
1597 char errbuf[BUFSIZ];
1600 #ifdef HAVE_RES_SEARCH
1601 if (err_no != 0 && h_errno != 0)
1602 report(stderr, _("fetchmail: internal inconsistency\n"));
1605 * Avoid generating a bogus error every poll cycle when we're
1606 * in daemon mode but the connection to the outside world
1609 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1610 && run.poll_interval))
1612 report_build(stderr, _("fetchmail: %s connection to %s failed"),
1613 protocol->name, ctl->server.pollname);
1614 #ifdef HAVE_RES_SEARCH
1617 if (h_errno == HOST_NOT_FOUND)
1618 strcpy(errbuf, _("host is unknown."));
1620 else if (h_errno == NO_ADDRESS)
1621 strcpy(errbuf, _("name is valid but has no IP address."));
1623 else if (h_errno == NO_RECOVERY)
1624 strcpy(errbuf, _("unrecoverable name server error."));
1625 else if (h_errno == TRY_AGAIN)
1626 strcpy(errbuf, _("temporary name server error."));
1628 sprintf(errbuf, _("unknown DNS error %d."), h_errno);
1631 #endif /* HAVE_RES_SEARCH */
1632 strcpy(errbuf, strerror(err_no));
1633 report_complete(stderr, ": %s\n", errbuf);
1637 * Don't use this. It was an attempt to address Debian bug
1638 * #47143 (Notify user by mail when pop server nonexistent).
1639 * Trouble is, that doesn't work; you trip over the case
1640 * where your SLIP or PPP link is down...
1642 /* warn the system administrator */
1643 if (open_warning_by_mail(ctl, (struct msgblk *)NULL) == 0)
1645 #define OPENFAIL "Subject: Fetchmail unreachable-server warning.\r\n\r\nFetchmail could not reach the mail server %s:"
1646 stuff_warning(ctl, OPENFAIL, ctl->server.pollname);
1647 stuff_warning(ctl, errbuf, ctl->server.pollname);
1648 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1653 #endif /* INET6_ENABLE */
1663 /* perform initial SSL handshake on open connection */
1664 /* Note: We pass the realhost name over for certificate
1665 verification. We may want to make this configurable */
1666 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslkey,ctl->sslcert,realhost) == -1)
1668 report(stderr, "SSL connection failed.");
1674 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1676 set_timeout(mytimeout);
1677 ok = kerberos_auth(mailserver_socket, ctl->server.truename);
1682 #endif /* KERBEROS_V4 */
1685 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1687 set_timeout(mytimeout);
1688 ok = kerberos5_auth(mailserver_socket, ctl->server.truename);
1693 #endif /* KERBEROS_V5 */
1695 /* accept greeting message from mail server */
1696 ok = (protocol->parse_response)(mailserver_socket, buf);
1700 /* try to get authorized to fetch mail */
1701 stage = STAGE_GETAUTH;
1702 if (protocol->getauth)
1704 if (protocol->password_canonify)
1705 (protocol->password_canonify)(shroud, ctl->password, PASSWORDLEN);
1707 strcpy(shroud, ctl->password);
1709 ok = (protocol->getauth)(mailserver_socket, ctl, buf);
1712 if (ok == PS_LOCKBUSY)
1713 report(stderr, _("Lock-busy error on %s@%s\n"),
1715 ctl->server.truename);
1716 else if (ok == PS_AUTHFAIL)
1718 report(stderr, _("Authorization failure on %s@%s\n"),
1720 ctl->server.truename);
1723 * If we're running in background, try to mail the
1724 * calling user a heads-up about the authentication
1725 * failure once it looks like this isn't a fluke
1726 * due to the server being temporarily inaccessible.
1728 if (run.poll_interval
1729 && ctl->authfailcount++ > MAX_AUTHFAILS
1730 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1733 _("Subject: fetchmail authentication failed\r\n"));
1735 _("Fetchmail could not get mail from %s@%s.\r\n"),
1737 ctl->server.truename);
1739 _("The attempt to get authorization failed.\r\n" \
1740 "This probably means your password is invalid, but POP3 servers have\r\n" \
1741 "other failure modes that fetchmail cannot distinguish from this\r\n" \
1742 "because they don't send useful error messages on login failure.\r\n"));
1743 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1748 report(stderr, _("Unknown login or authentication error on %s@%s\n"),
1750 ctl->server.truename);
1756 ctl->errcount = fetches = 0;
1758 /* now iterate over each folder selected */
1759 for (idp = ctl->mailboxes; idp; idp = idp->next)
1766 /* reset timeout, in case we did an IDLE */
1767 mytimeout = ctl->server.timeout;
1769 if (outlevel >= O_DEBUG)
1772 report(stdout, _("selecting or re-polling folder %s\n"), idp->id);
1774 report(stdout, _("selecting or re-polling default folder\n"));
1777 /* compute # of messages and number of new messages waiting */
1778 stage = STAGE_GETRANGE;
1779 ok = (protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
1783 /* show user how many messages we downloaded */
1785 (void) sprintf(buf, _("%s at %s (folder %s)"),
1786 ctl->remotename, ctl->server.truename, idp->id);
1788 (void) sprintf(buf, _("%s at %s"),
1789 ctl->remotename, ctl->server.truename);
1790 if (outlevel > O_SILENT)
1792 if (count == -1) /* only used for ETRN */
1793 report(stdout, _("Polling %s\n"), ctl->server.truename);
1794 else if (count != 0)
1796 if (new != -1 && (count - new) > 0)
1797 report_build(stdout, _("%d %s (%d seen) for %s"),
1798 count, count > 1 ? _("messages") :
1802 report_build(stdout, _("%d %s for %s"),
1803 count, count > 1 ? _("messages") :
1806 report_complete(stdout, ".\n");
1808 report_complete(stdout, _(" (%d octets).\n"), bytes);
1812 /* these are pointless in normal daemon mode */
1813 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1814 report(stdout, _("No mail for %s\n"), buf);
1818 /* very important, this is where we leave the do loop */
1824 if (new == -1 || ctl->fetchall)
1826 fetches = new; /* set error status ccorrectly */
1828 * There used to be a `got noerror' here, but this
1829 * prevneted checking of multiple folders. This
1830 * comment is a reminder in case I introduced some
1831 * subtle bug by removing it...
1836 flag force_retrieval;
1839 * What forces this code is that in POP2 and
1840 * IMAP2bis you can't fetch a message without
1841 * having it marked `seen'. In POP3 and IMAP4, on the
1842 * other hand, you can (peek_capable is set by
1843 * each driver module to convey this; it's not a
1844 * method constant because of the difference between
1845 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1846 * if fetchall is on).
1848 * The result of being unable to peek is that if there's
1849 * any kind of transient error (DNS lookup failure, or
1850 * sendmail refusing delivery due to process-table limits)
1851 * the message will be marked "seen" on the server without
1852 * having been delivered. This is not a big problem if
1853 * fetchmail is running in foreground, because the user
1854 * will see a "skipped" message when it next runs and get
1857 * But in daemon mode this leads to the message
1858 * being silently ignored forever. This is not
1861 * We compensate for this by checking the error
1862 * count from the previous pass and forcing all
1863 * messages to be considered new if it's nonzero.
1865 force_retrieval = !peek_capable && (ctl->errcount > 0);
1868 * We need the size of each message before it's
1869 * loaded in order to pass it to the ESMTP SIZE
1870 * option. If the protocol has a getsizes method,
1871 * we presume this means it doesn't get reliable
1872 * sizes from message fetch responses.
1874 if (proto->getsizes)
1878 xalloca(msgsizes, int *, sizeof(int) * count);
1879 for (i = 0; i < count; i++)
1882 stage = STAGE_GETSIZES;
1883 ok = (proto->getsizes)(mailserver_socket, count, msgsizes);
1890 for (i = 0; i < count; i++)
1891 bytes += msgsizes[i];
1895 /* read, forward, and delete messages */
1896 stage = STAGE_FETCH;
1897 for (num = 1; num <= count; num++)
1899 flag toolarge = NUM_NONZERO(ctl->limit)
1900 && msgsizes && (msgsizes[num-1] > ctl->limit);
1901 flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(mailserver_socket,ctl,num));
1902 flag fetch_it = !toolarge
1903 && (ctl->fetchall || force_retrieval || !oldmsg);
1904 flag suppress_delete = FALSE;
1905 flag suppress_forward = FALSE;
1906 flag suppress_readbody = FALSE;
1907 flag retained = FALSE;
1910 * This check copes with Post Office/NT's
1911 * annoying habit of randomly prepending bogus
1912 * LIST items of length -1. Patrick Audley
1913 * <paudley@pobox.com> tells us: LIST shows a
1914 * size of -1, RETR and TOP return "-ERR
1915 * System error - couldn't open message", and
1916 * DELE succeeds but doesn't actually delete
1919 if (msgsizes && msgsizes[num-1] == -1)
1921 if (outlevel >= O_VERBOSE)
1923 _("Skipping message %d, length -1\n"),
1929 * We may want to reject this message if it's old
1930 * or oversized, and we're not forcing retrieval.
1934 if (outlevel > O_SILENT)
1936 report_build(stdout, _("skipping message %d"), num);
1937 if (toolarge && !check_only)
1942 /* convert sz to string */
1943 sprintf(size, "%d", msgsizes[num-1]);
1945 /* build a list of skipped messages
1946 * val.id = size of msg (string cnvt)
1947 * val.status.num = warning_poll_count
1948 * val.status.mask = nbr of msg this size
1951 current = ctl->skipped;
1953 /* initialise warning_poll_count to the
1954 * current value so that all new msg will
1955 * be included in the next mail
1957 cnt = current? current->val.status.num : 0;
1959 /* if entry exists, increment the count */
1961 str_in_list(¤t, size, FALSE))
1964 current = current->next)
1966 if (strcmp(current->id, size) == 0)
1968 current->val.status.mark++;
1973 /* otherwise, create a new entry */
1974 /* initialise with current poll count */
1977 tmp = save_str(&ctl->skipped, size, 1);
1978 tmp->val.status.num = cnt;
1981 report_build(stdout, _(" (oversized, %d octets)"),
1988 flag wholesize = !protocol->fetch_body;
1990 /* request a message */
1991 ok = (protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
1995 /* -1 means we didn't see a size in the response */
1996 if (len == -1 && msgsizes)
1998 len = msgsizes[num - 1];
2002 if (outlevel > O_SILENT)
2004 report_build(stdout, _("reading message %d of %d"),
2008 report_build(stdout, _(" (%d %soctets)"),
2009 len, wholesize ? "" : _("header "));
2010 if (outlevel >= O_VERBOSE)
2011 report_complete(stdout, "\n");
2013 report_complete(stdout, " ");
2017 * Read the message headers and ship them to the
2020 ok = readheaders(mailserver_socket, len, msgsizes[num-1],
2022 if (ok == PS_RETAINED)
2023 suppress_forward = retained = TRUE;
2024 else if (ok == PS_TRANSIENT)
2025 suppress_delete = suppress_forward = TRUE;
2026 else if (ok == PS_REFUSED)
2027 suppress_forward = TRUE;
2028 else if (ok == PS_TRUNCATED)
2029 suppress_readbody = TRUE;
2034 * If we're using IMAP4 or something else that
2035 * can fetch headers separately from bodies,
2036 * it's time to request the body now. This
2037 * fetch may be skipped if we got an anti-spam
2038 * or other PS_REFUSED error response during
2041 if (protocol->fetch_body && !suppress_readbody)
2043 if (outlevel >= O_VERBOSE && isatty(1))
2045 fputc('\n', stdout);
2049 if ((ok = (protocol->trail)(mailserver_socket, ctl, num)))
2052 if (!suppress_forward)
2054 if ((ok=(protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
2057 * Work around a bug in Novell's
2058 * broken GroupWise IMAP server;
2059 * its body FETCH response is missing
2060 * the required length for the data
2061 * string. This violates RFC2060.
2064 len = msgsizes[num-1] - msglen;
2065 if (outlevel > O_SILENT && !wholesize)
2066 report_complete(stdout,
2067 _(" (%d body octets) "), len);
2071 /* process the body now */
2074 if (suppress_readbody)
2076 /* When readheaders returns PS_TRUNCATED,
2077 the body (which has no content
2078 has already been read by readheaders,
2079 so we say readbody returned PS_SUCCESS */
2084 ok = readbody(mailserver_socket,
2089 if (ok == PS_TRANSIENT)
2090 suppress_delete = suppress_forward = TRUE;
2094 /* tell server we got it OK and resynchronize */
2095 if (protocol->trail)
2097 if (outlevel >= O_VERBOSE && isatty(1))
2099 fputc('\n', stdout);
2103 ok = (protocol->trail)(mailserver_socket, ctl, num);
2109 /* count # messages forwarded on this pass */
2110 if (!suppress_forward)
2114 * Check to see if the numbers matched?
2116 * Yes, some servers foo this up horribly.
2117 * All IMAP servers seem to get it right, and
2118 * so does Eudora QPOP at least in 2.xx
2121 * Microsoft Exchange gets it completely
2122 * wrong, reporting compressed rather than
2123 * actual sizes (so the actual length of
2124 * message is longer than the reported size).
2125 * Another fine example of Microsoft brain death!
2127 * Some older POP servers, like the old UCB
2128 * POP server and the pre-QPOP QUALCOMM
2129 * versions, report a longer size in the LIST
2130 * response than actually gets shipped up.
2131 * It's unclear what is going on here, as the
2132 * QUALCOMM server (at least) seems to be
2133 * reporting the on-disk size correctly.
2135 if (msgsizes && msglen != msgsizes[num-1])
2137 if (outlevel >= O_DEBUG)
2139 _("message %d was not the expected length (%d actual != %d expected)\n"),
2140 num, msglen, msgsizes[num-1]);
2143 /* end-of-message processing starts here */
2144 if (!close_sink(ctl, &msgblk, !suppress_forward))
2147 suppress_delete = TRUE;
2153 * At this point in flow of control, either
2154 * we've bombed on a protocol error or had
2155 * delivery refused by the SMTP server
2156 * (unlikely -- I've never seen it) or we've
2157 * seen `accepted for delivery' and the
2158 * message is shipped. It's safe to mark the
2159 * message seen and delete it on the server
2163 /* tell the UID code we've seen this */
2168 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2169 if (sdp->val.status.num == num)
2170 sdp->val.status.mark = UID_SEEN;
2173 /* maybe we delete this message now? */
2176 if (outlevel > O_SILENT)
2177 report(stdout, _(" retained\n"));
2179 else if (protocol->delete
2181 && (fetch_it ? !ctl->keep : ctl->flush))
2184 if (outlevel > O_SILENT)
2185 report_complete(stdout, _(" flushed\n"));
2186 ok = (protocol->delete)(mailserver_socket, ctl, num);
2190 delete_str(&ctl->newsaved, num);
2191 #endif /* POP3_ENABLE */
2193 else if (outlevel > O_SILENT)
2194 report_complete(stdout, _(" not flushed\n"));
2196 /* perhaps this as many as we're ready to handle */
2197 if (maxfetch && maxfetch <= fetches && fetches < count)
2199 report(stdout, _("fetchlimit %d reached; %d messages left on server\n"),
2200 maxfetch, count - fetches);
2206 if (!check_only && ctl->skipped
2207 && run.poll_interval > 0 && !nodetach)
2209 clean_skipped_list(&ctl->skipped);
2210 send_size_warnings(ctl);
2215 * Only re-poll if we either had some actual forwards and
2216 * either allowed deletions and had no errors.
2217 * Otherwise it is far too easy to get into infinite loops.
2219 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2223 /* ordinary termination with no errors -- officially log out */
2224 ok = (protocol->logout_cmd)(mailserver_socket, ctl);
2226 * Hmmmm...arguably this would be incorrect if we had fetches but
2227 * no dispatches (due to oversized messages, etc.)
2230 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2231 SockClose(mailserver_socket);
2235 /* we only get here on error */
2236 if (ok != 0 && ok != PS_SOCKET)
2238 stage = STAGE_LOGOUT;
2239 (protocol->logout_cmd)(mailserver_socket, ctl);
2241 SockClose(mailserver_socket);
2244 msg = (const char *)NULL; /* sacrifice to -Wall */
2251 msg = _("authorization");
2254 msg = _("missing or bad RFC822 header");
2260 msg = _("client/server synchronization");
2263 msg = _("client/server protocol");
2266 msg = _("lock busy on server");
2269 msg = _("SMTP transaction");
2272 msg = _("DNS lookup");
2275 report(stderr, _("undefined error\n"));
2278 /* no report on PS_MAXFETCH or PS_UNDEFINED */
2279 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2280 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2281 || ok==PS_LOCKBUSY || ok==PS_SMTP || ok==PS_DNS)
2282 report(stderr, _("%s error while fetching from %s\n"), msg, ctl->server.pollname);
2285 /* execute post-initialization command, if any */
2286 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2288 report(stderr, _("post-connection command failed with status %d\n"), ok);
2289 if (ok == PS_SUCCESS)
2293 signal(SIGALRM, alrmsave);
2294 signal(SIGPIPE, pipesave);
2298 int do_protocol(ctl, proto)
2299 /* retrieve messages from server using given protocol method table */
2300 struct query *ctl; /* parsed options with merged-in defaults */
2301 const struct method *proto; /* protocol method table */
2306 if (ctl->server.preauthenticate == A_KERBEROS_V4)
2308 report(stderr, _("Kerberos V4 support not linked.\n"));
2311 #endif /* KERBEROS_V4 */
2314 if (ctl->server.preauthenticate == A_KERBEROS_V5)
2316 report(stderr, _("Kerberos V5 support not linked.\n"));
2319 #endif /* KERBEROS_V5 */
2321 /* lacking methods, there are some options that may fail */
2324 /* check for unsupported options */
2327 _("Option --flush is not supported with %s\n"),
2331 else if (ctl->fetchall) {
2333 _("Option --all is not supported with %s\n"),
2338 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
2341 _("Option --limit is not supported with %s\n"),
2347 * If no expunge limit or we do expunges within the driver,
2348 * then just do one session, passing in any fetchlimit.
2350 if (proto->retry || !NUM_SPECIFIED(ctl->expunge))
2351 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
2353 * There's an expunge limit, and it isn't handled in the driver itself.
2354 * OK; do multiple sessions, each fetching a limited # of messages.
2355 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
2356 * (if it was nonzero).
2362 int expunge = NUM_VALUE_OUT(ctl->expunge);
2363 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
2366 ok = do_session(ctl, proto, expunge);
2367 totalcount += expunge;
2368 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
2370 if (ok != PS_LOCKBUSY)
2372 else if (lockouts >= MAX_LOCKOUTS)
2374 else /* ok == PS_LOCKBUSY */
2377 * Allow time for the server lock to release. if we
2378 * don't do this, we'll often hit a locked-mailbox
2379 * condition and fail.
2385 (ok == PS_MAXFETCH || ok == PS_LOCKBUSY);
2391 #if defined(HAVE_STDARG_H)
2392 void gen_send(int sock, const char *fmt, ... )
2394 void gen_send(sock, fmt, va_alist)
2395 int sock; /* socket to which server is connected */
2396 const char *fmt; /* printf-style format */
2399 /* assemble command in printf(3) style and send to the server */
2401 char buf [MSGBUFSIZE+1];
2404 if (protocol->tagged)
2405 (void) sprintf(buf, "%s ", GENSYM);
2409 #if defined(HAVE_STDARG_H)
2414 #ifdef HAVE_VSNPRINTF
2415 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2417 vsprintf(buf + strlen(buf), fmt, ap);
2421 strcat(buf, "\r\n");
2422 SockWrite(sock, buf, strlen(buf));
2424 if (outlevel >= O_MONITOR)
2428 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2432 sp = cp + strlen(shroud);
2438 buf[strlen(buf)-2] = '\0';
2439 report(stdout, "%s> %s\n", protocol->name, buf);
2443 int gen_recv(sock, buf, size)
2444 /* get one line of input from the server */
2445 int sock; /* socket to which server is connected */
2446 char *buf; /* buffer to receive input */
2447 int size; /* length of buffer */
2449 int oldphase = phase; /* we don't have to be re-entrant */
2451 phase = SERVER_WAIT;
2452 set_timeout(mytimeout);
2453 if (SockRead(sock, buf, size) == -1)
2462 if (buf[strlen(buf)-1] == '\n')
2463 buf[strlen(buf)-1] = '\0';
2464 if (buf[strlen(buf)-1] == '\r')
2465 buf[strlen(buf)-1] = '\0';
2466 if (outlevel >= O_MONITOR)
2467 report(stdout, "%s< %s\n", protocol->name, buf);
2473 #if defined(HAVE_STDARG_H)
2474 int gen_transact(int sock, const char *fmt, ... )
2476 int gen_transact(int sock, fmt, va_alist)
2477 int sock; /* socket to which server is connected */
2478 const char *fmt; /* printf-style format */
2481 /* assemble command in printf(3) style, send to server, accept a response */
2484 char buf [MSGBUFSIZE+1];
2486 int oldphase = phase; /* we don't have to be re-entrant */
2488 phase = SERVER_WAIT;
2490 if (protocol->tagged)
2491 (void) sprintf(buf, "%s ", GENSYM);
2495 #if defined(HAVE_STDARG_H)
2500 #ifdef HAVE_VSNPRINTF
2501 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2503 vsprintf(buf + strlen(buf), fmt, ap);
2507 strcat(buf, "\r\n");
2508 SockWrite(sock, buf, strlen(buf));
2510 if (outlevel >= O_MONITOR)
2514 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2518 sp = cp + strlen(shroud);
2524 buf[strlen(buf)-1] = '\0';
2525 report(stdout, "%s> %s\n", protocol->name, buf);
2528 /* we presume this does its own response echoing */
2529 ok = (protocol->parse_response)(sock, buf);
2535 /* driver.c ends here */