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, *delivered_to;
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;
453 * We used to free the header block unconditionally at the end of
454 * readheaders, but it turns out that if close_sink() hits an error
455 * condition the code for sending bouncemail will actually look
456 * at the freed storage and coredump...
459 free(msgblk.headers);
461 msgblk.headers = received_for = delivered_to = NULL;
462 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
463 sender_offs = resent_sender_offs = env_offs = -1;
469 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
473 line = xmalloc(sizeof(buf));
477 set_timeout(mytimeout);
478 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
481 free(msgblk.headers);
482 msgblk.headers = NULL;
489 /* lines may not be properly CRLF terminated; fix this for qmail */
492 cp = buf + strlen(buf) - 1;
493 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
502 * Decode MIME encoded headers. We MUST do this before
503 * looking at the Content-Type / Content-Transfer-Encoding
504 * headers (RFC 2046).
509 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
513 /* check for end of headers */
517 has_nuls = (linelen != strlen(line));
519 goto process_headers;
523 * Check for end of message immediately. If one of your folders
524 * has been mangled, the delimiter may occur directly after the
527 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
530 has_nuls = (linelen != strlen(line));
531 goto process_headers;
534 /* check for RFC822 continuations */
535 set_timeout(mytimeout);
539 (ch == ' ' || ch == '\t'); /* continuation to next line? */
541 /* write the message size dots */
542 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
544 sizeticker += linelen;
545 while (sizeticker >= SIZETICKER)
547 if ((!run.use_syslog && !isafile(1)) || run.showdots)
552 sizeticker -= SIZETICKER;
556 /* we see an ordinary (non-header, non-message-delimiter line */
557 has_nuls = (linelen != strlen(line));
560 * When mail delivered to a multidrop mailbox on the server is
561 * addressed to multiple people on the client machine, there
562 * will be one copy left in the box for each recipient. Thus,
563 * if the mail is addressed to N people, each recipient will
564 * get N copies. This is bad when N > 1.
566 * Foil this by suppressing all but one copy of a message with
567 * a given Message-ID. The accept_count test ensures that
568 * multiple pieces of email with the same Message-ID, each
569 * with a *single* addressee (the N == 1 case), won't be
572 * Note: This implementation only catches runs of successive
573 * messages with the same ID, but that should be good
574 * enough. A more general implementation would have to store
575 * ever-growing lists of seen message-IDs; in a long-running
576 * daemon this would turn into a memory leak even if the
577 * implementation were perfect.
579 * Don't mess with this code casually. It would be way too easy
580 * to break it in a way that blackholed mail. Better to pass
581 * the occasional duplicate than to do that...
583 if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
585 if (ctl->lastid && !strcasecmp(ctl->lastid, line))
587 if (accept_count > 1)
594 ctl->lastid = strdup(line);
599 * The University of Washington IMAP server (the reference
600 * implementation of IMAP4 written by Mark Crispin) relies
601 * on being able to keep base-UID information in a special
602 * message at the head of the mailbox. This message should
603 * neither be deleted nor forwarded.
607 * We disable this check under POP2 because there's no way to
608 * prevent deletion of the message. So at least we ought to
609 * forward it to the user so he or she will have some clue
610 * that things have gone awry.
613 if (strncmp(protocol->service, "pop2", 4))
614 #else /* INET6_ENABLE */
615 if (protocol->port != 109)
616 #endif /* INET6_ENABLE */
617 #endif /* POP2_ENABLE */
618 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
620 free(msgblk.headers);
621 msgblk.headers = NULL;
626 * This code prevents fetchmail from becoming an accessory after
627 * the fact to upstream sendmails with the `E' option on. It also
628 * copes with certain brain-dead POP servers (like NT's) that pass
629 * through Unix from_ lines.
631 * Either of these bugs can result in a non-RFC822 line at the
632 * beginning of the headers. If fetchmail just passes it
633 * through, the client listener may think the message has *no*
634 * headers (since the first) line it sees doesn't look
635 * RFC822-conformant) and fake up a set.
637 * What the user would see in this case is bogus (synthesized)
638 * headers, followed by a blank line, followed by the >From,
639 * followed by the real headers, followed by a blank line,
642 * We forestall this lossage by tossing anything that looks
643 * like an escaped or passed-through From_ line in headers.
644 * These aren't RFC822 so our conscience is clear...
646 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
653 * We remove all Delivered-To: headers.
655 * This is to avoid false mail loops messages when delivering
656 * local messages to and from a Postfix/qmail mailserver.
658 * Should be controlled by an option
660 if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) {
661 if (delivered_to) free(line);
662 else delivered_to = line;
667 * If we see a Status line, it may have been inserted by an MUA
668 * on the mail host, or it may have been inserted by the server
669 * program after the headers in the transaction stream. This
670 * can actually hose some new-mail notifiers such as xbuffy,
671 * which assumes any Status line came from a *local* MDA and
672 * therefore indicates that the message has been seen.
674 * Some buggy POP servers (including at least the 3.3(20)
675 * version of the one distributed with IMAP) insert empty
676 * Status lines in the transaction stream; we'll chuck those
677 * unconditionally. Nonempty ones get chucked if the user
678 * turns on the dropstatus flag.
683 if (!strncasecmp(line, "Status:", 7))
685 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
690 while (*cp && isspace(*cp)) cp++;
691 if (!*cp || ctl->dropstatus)
700 line = reply_hack(line, ctl->server.truename);
703 * OK, this is messy. If we're forwarding by SMTP, it's the
704 * SMTP-receiver's job (according to RFC821, page 22, section
705 * 4.1.1) to generate a Return-Path line on final delivery.
706 * The trouble is, we've already got one because the
707 * mailserver's SMTP thought *it* was responsible for final
710 * Stash away the contents of Return-Path (as modified by reply_hack)
711 * for use in generating MAIL FROM later on, then prevent the header
712 * from being saved with the others. In effect, we strip it off here.
714 * If the SMTP server conforms to the standards, and fetchmail gets the
715 * envelope sender from the Return-Path, the new Return-Path should be
716 * exactly the same as the original one.
718 * We do *not* want to ignore empty Return-Path headers. These should
719 * be passed through as a way of indicating that a message should
720 * not trigger bounces if delivery fails. What we *do* need to do is
721 * make sure we never try to rewrite such a blank Return-Path. We
722 * handle this with a check for <> in the rewrite logic above.
724 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
726 strcpy(msgblk.return_path, cp);
735 oldlen = strlen(line);
736 msgblk.headers = xmalloc(oldlen + 1);
737 (void) strcpy(msgblk.headers, line);
739 line = msgblk.headers;
745 newlen = oldlen + strlen(line);
746 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
747 if (msgblk.headers == NULL) {
751 strcpy(msgblk.headers + oldlen, line);
753 line = msgblk.headers + oldlen;
757 if (!strncasecmp("From:", line, 5))
758 from_offs = (line - msgblk.headers);
759 else if (!strncasecmp("Reply-To:", line, 9))
760 reply_to_offs = (line - msgblk.headers);
761 else if (!strncasecmp("Resent-From:", line, 12))
762 resent_from_offs = (line - msgblk.headers);
763 else if (!strncasecmp("Apparently-From:", line, 16))
764 app_from_offs = (line - msgblk.headers);
765 else if (!strncasecmp("Sender:", line, 7))
766 sender_offs = (line - msgblk.headers);
767 else if (!strncasecmp("Resent-Sender:", line, 14))
768 resent_sender_offs = (line - msgblk.headers);
771 else if (!strncasecmp("Message-Id:", line, 11))
773 if (ctl->server.uidl)
777 line[IDLEN+12] = 0; /* prevent stack overflow */
778 sscanf(line+12, "%s", id);
779 if (!str_find( &ctl->newsaved, num))
781 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
782 new->val.status.num = num;
786 #endif /* __UNUSED__ */
788 else if (!MULTIDROP(ctl))
791 else if (!strncasecmp("To:", line, 3)
792 || !strncasecmp("Cc:", line, 3)
793 || !strncasecmp("Bcc:", line, 4)
794 || !strncasecmp("Apparently-To:", line, 14))
796 *to_chainptr = xmalloc(sizeof(struct addrblk));
797 (*to_chainptr)->offset = (line - msgblk.headers);
798 to_chainptr = &(*to_chainptr)->next;
802 else if (!strncasecmp("Resent-To:", line, 10)
803 || !strncasecmp("Resent-Cc:", line, 10)
804 || !strncasecmp("Resent-Bcc:", line, 11))
806 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
807 (*resent_to_chainptr)->offset = (line - msgblk.headers);
808 resent_to_chainptr = &(*resent_to_chainptr)->next;
809 *resent_to_chainptr = NULL;
812 else if (ctl->server.envelope != STRING_DISABLED)
814 if (ctl->server.envelope
815 && strcasecmp(ctl->server.envelope, "Received"))
817 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
819 strlen(ctl->server.envelope)))
821 if (skipcount++ != ctl->server.envskip)
823 env_offs = (line - msgblk.headers);
826 else if (!received_for && !strncasecmp("Received:", line, 9))
828 if (skipcount++ != ctl->server.envskip)
830 received_for = parse_received(ctl, line);
837 * We want to detect this early in case there are so few headers that the
838 * dispatch logic barfs.
842 if (outlevel > O_SILENT)
844 _("message delimiter found while scanning headers\n"));
848 * Hack time. If the first line of the message was blank, with no headers
849 * (this happens occasionally due to bad gatewaying software) cons up
850 * a set of fake headers.
852 * If you modify the fake header template below, be sure you don't
853 * make either From or To address @-less, otherwise the reply_hack
854 * logic will do bad things.
856 if (msgblk.headers == (char *)NULL)
859 snprintf(buf, sizeof(buf),
862 #endif /* HAVE_SNPRINTF */
863 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
864 user, fetchmailhost, ctl->remotename, ctl->server.truename);
865 msgblk.headers = xstrdup(buf);
869 * We can now process message headers before reading the text.
870 * In fact we have to, as this will tell us where to forward to.
873 /* Check for MIME headers indicating possible 8-bit data */
874 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
877 if (ctl->server.sdps && sdps_envfrom)
879 /* We have the real envelope return-path, stored out of band by
880 * SDPS - that's more accurate than any header is going to be.
882 strcpy(msgblk.return_path, sdps_envfrom);
885 #endif /* SDPS_ENABLE */
887 * If there is a Return-Path address on the message, this was
888 * almost certainly the MAIL FROM address given the originating
889 * sendmail. This is the best thing to use for logging the
890 * message origin (it sets up the right behavior for bounces and
891 * mailing lists). Otherwise, fall down to the next available
892 * envelope address (which is the most probable real sender).
893 * *** The order is important! ***
894 * This is especially useful when receiving mailing list
895 * messages in multidrop mode. if a local address doesn't
896 * exist, the bounce message won't be returned blindly to the
897 * author or to the list itself but rather to the list manager
898 * (ex: specified by "Sender:") which is much less annoying. This
899 * is true for most mailing list packages.
901 if( !msgblk.return_path[0] ){
903 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
904 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
905 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
906 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
907 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
908 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
909 if (ap) strcpy( msgblk.return_path, ap );
912 /* cons up a list of local recipients */
913 msgblk.recipients = (struct idlist *)NULL;
914 accept_count = reject_count = 0;
915 /* is this a multidrop box? */
919 if (ctl->server.sdps && sdps_envto)
921 /* We have the real envelope recipient, stored out of band by
922 * SDPS - that's more accurate than any header is going to be.
924 find_server_names(sdps_envto, ctl, &msgblk.recipients);
927 #endif /* SDPS_ENABLE */
928 if (env_offs > -1) /* We have the actual envelope addressee */
929 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
930 else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
931 ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
933 find_server_names(delivered_to, ctl, &msgblk.recipients);
936 else if (received_for)
938 * We have the Received for addressee.
939 * It has to be a mailserver address, or we
940 * wouldn't have got here.
941 * We use find_server_names() to let local
942 * hostnames go through.
944 find_server_names(received_for, ctl, &msgblk.recipients);
948 * We haven't extracted the envelope address.
949 * So check all the "Resent-To" header addresses if
950 * they exist. If and only if they don't, consider
951 * the "To" addresses.
953 register struct addrblk *nextptr;
954 if (resent_to_addrchain) {
955 /* delete the "To" chain and substitute it
956 * with the "Resent-To" list
958 while (to_addrchain) {
959 nextptr = to_addrchain->next;
961 to_addrchain = nextptr;
963 to_addrchain = resent_to_addrchain;
964 resent_to_addrchain = NULL;
966 /* now look for remaining adresses */
967 while (to_addrchain) {
968 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
969 nextptr = to_addrchain->next;
971 to_addrchain = nextptr;
976 no_local_matches = TRUE;
977 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
978 if (outlevel >= O_DEBUG)
980 _("no local matches, forwarding to %s\n"),
984 else /* it's a single-drop box, use first localname */
985 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
989 * Time to either address the message or decide we can't deliver it yet.
991 if (ctl->errcount > olderrs) /* there were DNS errors above */
993 if (outlevel >= O_DEBUG)
995 _("forwarding and deletion suppressed due to DNS errors\n"));
996 free(msgblk.headers);
997 msgblk.headers = NULL;
998 free_str_list(&msgblk.recipients);
999 return(PS_TRANSIENT);
1003 /* set up stuffline() so we can deliver the message body through it */
1004 if ((n = open_sink(ctl, &msgblk,
1005 &good_addresses, &bad_addresses)) != PS_SUCCESS)
1007 free(msgblk.headers);
1008 msgblk.headers = NULL;
1009 free_str_list(&msgblk.recipients);
1016 * Some server/sendmail combinations cause problems when our
1017 * synthetic Received line is before the From header. Cope
1020 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
1021 rcv = msgblk.headers;
1022 /* handle ">Received:" lines too */
1023 while (rcv > msgblk.headers && rcv[-1] != '\n')
1025 if (rcv > msgblk.headers)
1030 n = stuffline(ctl, msgblk.headers);
1033 if (!run.invisible && n != -1)
1035 /* utter any per-message Received information we need here */
1036 if (ctl->server.trueaddr) {
1037 sprintf(buf, "Received: from %s [%u.%u.%u.%u]\r\n",
1038 ctl->server.truename,
1039 (unsigned char)ctl->server.trueaddr[0],
1040 (unsigned char)ctl->server.trueaddr[1],
1041 (unsigned char)ctl->server.trueaddr[2],
1042 (unsigned char)ctl->server.trueaddr[3]);
1044 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
1046 n = stuffline(ctl, buf);
1050 * This header is technically invalid under RFC822.
1051 * POP3, IMAP, etc. are not legal mail-parameter values.
1053 * We used to include ctl->remotename in this log line,
1054 * but this can be secure information that would be bad
1057 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
1061 n = stuffline(ctl, buf);
1065 if (good_addresses == 0)
1068 "for %s@%s (by default); ",
1069 user, ctl->destaddr);
1071 else if (good_addresses == 1)
1073 for (idp = msgblk.recipients; idp; idp = idp->next)
1074 if (idp->val.status.mark == XMIT_ACCEPT)
1075 break; /* only report first address */
1076 if (strchr(idp->id, '@'))
1077 sprintf(buf+1, "for %s", idp->id);
1080 * This could be a bit misleading, as destaddr is
1081 * the forwarding host rather than the actual
1082 * destination. Most of the time they coincide.
1084 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
1085 sprintf(buf+strlen(buf), " (%s); ",
1086 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1091 strcat(buf, rfc822timestamp());
1092 strcat(buf, "\r\n");
1093 n = stuffline(ctl, buf);
1099 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1103 report(stdout, _("writing RFC822 msgblk.headers\n"));
1105 free(msgblk.headers);
1106 msgblk.headers = NULL;
1107 free_str_list(&msgblk.recipients);
1110 else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && !isafile(2))
1113 /* write error notifications */
1114 if (no_local_matches || has_nuls || bad_addresses)
1117 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1120 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1121 if (no_local_matches)
1123 if (reject_count != 1)
1124 strcat(errhd, _("no recipient addresses matched declared local names"));
1127 for (idp = msgblk.recipients; idp; idp = idp->next)
1128 if (idp->val.status.mark == XMIT_REJECT)
1130 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1136 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1137 strcat(errhd, "; ");
1138 strcat(errhd, _("message has embedded NULs"));
1143 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1144 strcat(errhd, "; ");
1145 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1146 errlen = strlen(errhd);
1147 for (idp = msgblk.recipients; idp; idp = idp->next)
1148 if (idp->val.status.mark == XMIT_RCPTBAD)
1149 errlen += strlen(idp->id) + 2;
1151 xalloca(errmsg, char *, errlen+3);
1152 (void) strcpy(errmsg, errhd);
1153 for (idp = msgblk.recipients; idp; idp = idp->next)
1154 if (idp->val.status.mark == XMIT_RCPTBAD)
1156 strcat(errmsg, idp->id);
1158 strcat(errmsg, ", ");
1163 strcat(errmsg, "\r\n");
1165 /* ship out the error line */
1166 stuffline(ctl, errmsg);
1169 /* issue the delimiter line */
1174 stuffline(ctl, buf);
1176 /* free(msgblk.headers); */
1177 free_str_list(&msgblk.recipients);
1178 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1181 static int readbody(int sock, struct query *ctl, flag forward, int len)
1182 /* read and dispose of a message body presented on sock */
1183 /* ctl: query control record */
1184 /* sock: to which the server is connected */
1185 /* len: length of message */
1186 /* forward: TRUE to forward */
1189 unsigned char buf[MSGBUFSIZE+4];
1190 unsigned char *inbufp = buf;
1191 flag issoftline = FALSE;
1194 * Pass through the text lines in the body.
1196 * Yes, this wants to be ||, not &&. The problem is that in the most
1197 * important delimited protocol, POP3, the length is not reliable.
1198 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1199 * So, for delimited protocols we need to ignore the length here and
1200 * instead drop out of the loop with a break statement when we see
1201 * the message delimiter.
1203 while (protocol->delimited || len > 0)
1205 set_timeout(mytimeout);
1206 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1214 /* write the message size dots */
1217 sizeticker += linelen;
1218 while (sizeticker >= SIZETICKER)
1220 if (outlevel > O_SILENT && (((run.poll_interval == 0 || nodetach) && !isafile(1)) || run.showdots))
1225 sizeticker -= SIZETICKER;
1230 /* check for end of message */
1231 if (protocol->delimited && *inbufp == '.')
1233 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1235 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1238 msglen--; /* subtract the size of the dot escape */
1243 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1244 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1245 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1248 * Soft linebreak, but less than 200 bytes left in
1249 * input buffer. Rather than doing a buffer overrun,
1250 * ignore the soft linebreak, NL-terminate data and
1251 * deliver what we have now.
1252 * (Who writes lines longer than 2K anyway?)
1254 *inbufp = '\n'; *(inbufp+1) = '\0';
1259 /* ship out the text line */
1260 if (forward && (!issoftline))
1265 /* guard against very long lines */
1266 buf[MSGBUFSIZE+1] = '\r';
1267 buf[MSGBUFSIZE+2] = '\n';
1268 buf[MSGBUFSIZE+3] = '\0';
1270 n = stuffline(ctl, buf);
1274 report(stdout, _("writing message text\n"));
1278 else if (outlevel >= O_VERBOSE && !isafile(1))
1291 kerberos_auth (socket, canonical, principal)
1292 /* authenticate to the server host using Kerberos V4 */
1293 int socket; /* socket to server host */
1294 #if defined(__FreeBSD__) || defined(__OpenBSD__)
1295 char *canonical; /* server name */
1297 const char *canonical; /* server name */
1301 char * host_primary;
1305 Key_schedule schedule;
1307 char * prin_copy = (char *) NULL;
1308 char * prin = (char *) NULL;
1309 char * inst = (char *) NULL;
1310 char * realm = (char *) NULL;
1312 if (principal != (char *)NULL && *principal)
1315 prin = prin_copy = xstrdup(principal);
1316 for (cp = prin_copy; *cp && *cp != '.'; ++cp)
1322 while (*cp && *cp != '@')
1332 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1333 rem = (krb_sendauth (0L, socket, ticket,
1334 prin ? prin : "pop",
1335 inst ? inst : canonical,
1336 realm ? realm : ((char *) (krb_realmofhost (canonical))),
1337 ((unsigned long) 0),
1341 ((struct sockaddr_in *) 0),
1342 ((struct sockaddr_in *) 0),
1348 if (rem != KSUCCESS)
1350 report(stderr, _("kerberos error %s\n"), (krb_get_err_text (rem)));
1351 return (PS_AUTHFAIL);
1355 #endif /* KERBEROS_V4 */
1358 static int kerberos5_auth(socket, canonical)
1359 /* authenticate to the server host using Kerberos V5 */
1360 int socket; /* socket to server host */
1361 const char *canonical; /* server name */
1363 krb5_error_code retval;
1364 krb5_context context;
1366 krb5_principal client = NULL, server = NULL;
1367 krb5_error *err_ret = NULL;
1369 krb5_auth_context auth_context = NULL;
1371 krb5_init_context(&context);
1372 krb5_init_ets(context);
1373 krb5_auth_con_init(context, &auth_context);
1375 if (retval = krb5_cc_default(context, &ccdef)) {
1376 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
1380 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1381 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
1385 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1388 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
1392 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1393 "KPOPV1.0", client, server,
1394 AP_OPTS_MUTUAL_REQUIRED,
1395 NULL, /* no data to checksum */
1396 0, /* no creds, use ccache instead */
1400 NULL); /* don't need reply */
1402 krb5_free_principal(context, server);
1403 krb5_free_principal(context, client);
1404 krb5_auth_con_free(context, auth_context);
1408 if (err_ret && err_ret->e_text) {
1409 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1410 error_message(retval),
1413 if (err_ret && err_ret->text.length) {
1414 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1415 error_message(retval),
1416 err_ret->text.length,
1417 err_ret->text.data);
1419 krb5_free_error(context, err_ret);
1421 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
1427 #endif /* KERBEROS_V5 */
1429 static void clean_skipped_list(struct idlist **skipped_list)
1430 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1432 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1433 prev = current = head = *skipped_list;
1439 /* if item has no reference, remove it */
1440 if (current && current->val.status.mark == 0)
1442 if (current == head) /* remove first item (head) */
1444 head = current->next;
1445 if (current->id) free(current->id);
1447 prev = current = head;
1449 else /* remove middle/last item */
1451 tmp = current->next;
1453 if (current->id) free(current->id);
1458 else /* skip this item */
1461 current = current->next;
1465 *skipped_list = head;
1468 static void send_size_warnings(struct query *ctl)
1469 /* send warning mail with skipped msg; reset msg count when user notified */
1472 int msg_to_send = FALSE;
1473 struct idlist *head=NULL, *current=NULL;
1474 int max_warning_poll_count;
1476 head = ctl->skipped;
1480 /* don't start a notification message unless we need to */
1481 for (current = head; current; current = current->next)
1482 if (current->val.status.num == 0 && current->val.status.mark)
1488 * There's no good way to recover if we can't send notification mail,
1489 * but it's not a disaster, either, since the skipped mail will not
1492 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1495 _("Subject: Fetchmail oversized-messages warning.\r\n"
1497 "The following oversized messages remain on the mail server %s:"),
1498 ctl->server.pollname);
1500 if (run.poll_interval == 0)
1501 max_warning_poll_count = 0;
1503 max_warning_poll_count = ctl->warnings/run.poll_interval;
1505 /* parse list of skipped msg, adding items to the mail */
1506 for (current = head; current; current = current->next)
1508 if (current->val.status.num == 0 && current->val.status.mark)
1510 nbr = current->val.status.mark;
1511 size = atoi(current->id);
1513 _("\t%d msg %d octets long skipped by fetchmail.\r\n"),
1516 current->val.status.num++;
1517 current->val.status.mark = 0;
1519 if (current->val.status.num >= max_warning_poll_count)
1520 current->val.status.num = 0;
1523 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1526 static int do_session(ctl, proto, maxfetch)
1527 /* retrieve messages from server using given protocol method table */
1528 struct query *ctl; /* parsed options with merged-in defaults */
1529 const struct method *proto; /* protocol method table */
1530 const int maxfetch; /* maximum number of messages to fetch */
1533 #ifdef HAVE_VOLATILE
1534 volatile int ok, mailserver_socket = -1; /* pacifies -Wall */
1536 int ok, mailserver_socket = -1;
1537 #endif /* HAVE_VOLATILE */
1539 void (*pipesave)(int);
1540 void (*alrmsave)(int);
1541 struct idlist *current=NULL, *tmp=NULL;
1544 ctl->server.base_protocol = protocol;
1548 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1551 /* set up the server-nonresponse timeout */
1552 alrmsave = signal(SIGALRM, timeout_handler);
1553 mytimeout = ctl->server.timeout;
1555 /* set up the broken-pipe timeout */
1556 pipesave = signal(SIGPIPE, sigpipe_handler);
1558 if ((js = setjmp(restart)))
1560 #ifdef HAVE_SIGPROCMASK
1562 * Don't rely on setjmp() to restore the blocked-signal mask.
1563 * It does this under BSD but is required not to under POSIX.
1565 * If your Unix doesn't have sigprocmask, better hope it has
1566 * BSD-like behavior. Otherwise you may see fetchmail get
1567 * permanently wedged after a second timeout on a bad read,
1568 * because alarm signals were blocked after the first.
1572 sigfillset(&allsigs);
1573 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1574 #endif /* HAVE_SIGPROCMASK */
1576 if (js == THROW_SIGPIPE)
1578 signal(SIGPIPE, SIG_IGN);
1580 _("SIGPIPE thrown from an MDA or a stream socket error\n"));
1584 else if (js == THROW_TIMEOUT)
1586 if (phase == OPEN_WAIT)
1588 _("timeout after %d seconds waiting to connect to server %s.\n"),
1589 ctl->server.timeout, ctl->server.pollname);
1590 else if (phase == SERVER_WAIT)
1592 _("timeout after %d seconds waiting for server %s.\n"),
1593 ctl->server.timeout, ctl->server.pollname);
1594 else if (phase == FORWARDING_WAIT)
1596 _("timeout after %d seconds waiting for %s.\n"),
1597 ctl->server.timeout,
1598 ctl->mda ? "MDA" : "SMTP");
1599 else if (phase == LISTENER_WAIT)
1601 _("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
1604 _("timeout after %d seconds.\n"), ctl->server.timeout);
1607 * If we've exceeded our threshold for consecutive timeouts,
1608 * try to notify the user, then mark the connection wedged.
1609 * Don't do this if the connection can idle, though; idle
1610 * timeouts just mean the frequency of mail is low.
1612 if (timeoutcount > MAX_TIMEOUTS
1613 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1616 _("Subject: fetchmail sees repeated timeouts\r\n"));
1618 _("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\r\n"),
1621 ctl->server.truename);
1623 _("This could mean that your mailserver is stuck, or that your SMTP\r\n" \
1624 "server is wedged, or that your mailbox file on the server has been\r\n" \
1625 "corrupted by a server error. You can run `fetchmail -v -v' to\r\n" \
1626 "diagnose the problem.\r\n\r\n" \
1627 "Fetchmail won't poll this mailbox again until you restart it.\r\n"));
1628 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1635 /* try to clean up all streams */
1637 if (ctl->smtp_socket != -1)
1638 SockClose(ctl->smtp_socket);
1639 if (mailserver_socket != -1)
1640 SockClose(mailserver_socket);
1644 char buf[MSGBUFSIZE+1], *realhost;
1645 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1647 int fetches, dispatches, oldphase;
1648 #else /* INET6_ENABLE */
1649 int port, fetches, dispatches, oldphase;
1650 #endif /* INET6_ENABLE */
1653 /* execute pre-initialization command, if any */
1654 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1657 _("pre-connection command failed with status %d\n"), ok);
1662 /* open a socket to the mail server */
1665 set_timeout(mytimeout);
1668 port = ctl->server.port ? ctl->server.port : ( ctl->use_ssl ? protocol->sslport : protocol->port );
1670 port = ctl->server.port ? ctl->server.port : protocol->port;
1672 #endif /* !INET6_ENABLE */
1673 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1675 /* allow time for the port to be set up if we have a plugin */
1676 if (ctl->server.plugin)
1679 if ((mailserver_socket = SockOpen(realhost,
1680 ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? protocol->sslservice : protocol->service ),
1681 ctl->server.netsec, ctl->server.plugin)) == -1)
1682 #else /* INET6_ENABLE */
1683 if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1684 #endif /* INET6_ENABLE */
1686 char errbuf[BUFSIZ];
1689 #ifdef HAVE_RES_SEARCH
1690 if (err_no != 0 && h_errno != 0)
1691 report(stderr, _("fetchmail: internal inconsistency\n"));
1694 * Avoid generating a bogus error every poll cycle when we're
1695 * in daemon mode but the connection to the outside world
1698 if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH)
1699 && run.poll_interval))
1701 report_build(stderr, _("fetchmail: %s connection to %s failed"),
1702 protocol->name, ctl->server.pollname);
1703 #ifdef HAVE_RES_SEARCH
1706 if (h_errno == HOST_NOT_FOUND)
1707 strcpy(errbuf, _("host is unknown."));
1709 else if (h_errno == NO_ADDRESS)
1710 strcpy(errbuf, _("name is valid but has no IP address."));
1712 else if (h_errno == NO_RECOVERY)
1713 strcpy(errbuf, _("unrecoverable name server error."));
1714 else if (h_errno == TRY_AGAIN)
1715 strcpy(errbuf, _("temporary name server error."));
1717 sprintf(errbuf, _("unknown DNS error %d."), h_errno);
1720 #endif /* HAVE_RES_SEARCH */
1721 strcpy(errbuf, strerror(err_no));
1722 report_complete(stderr, ": %s\n", errbuf);
1726 * Don't use this. It was an attempt to address Debian bug
1727 * #47143 (Notify user by mail when pop server nonexistent).
1728 * Trouble is, that doesn't work; you trip over the case
1729 * where your SLIP or PPP link is down...
1731 /* warn the system administrator */
1732 if (open_warning_by_mail(ctl, (struct msgblk *)NULL) == 0)
1735 _("Subject: Fetchmail unreachable-server warning.\r\n"
1737 "Fetchmail could not reach the mail server %s:")
1738 ctl->server.pollname);
1739 stuff_warning(ctl, errbuf, ctl->server.pollname);
1740 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1744 #endif /* INET6_ENABLE */
1754 /* perform initial SSL handshake on open connection */
1755 /* Note: We pass the realhost name over for certificate
1756 verification. We may want to make this configurable */
1757 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslkey,ctl->sslcert,realhost) == -1)
1759 report(stderr, _("SSL connection failed.\n"));
1765 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1767 set_timeout(mytimeout);
1768 ok = kerberos_auth(mailserver_socket, ctl->server.truename,
1769 ctl->server.principal);
1774 #endif /* KERBEROS_V4 */
1777 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1779 set_timeout(mytimeout);
1780 ok = kerberos5_auth(mailserver_socket, ctl->server.truename);
1785 #endif /* KERBEROS_V5 */
1787 /* accept greeting message from mail server */
1788 ok = (protocol->parse_response)(mailserver_socket, buf);
1792 /* try to get authorized to fetch mail */
1793 stage = STAGE_GETAUTH;
1794 if (protocol->getauth)
1796 if (protocol->password_canonify)
1797 (protocol->password_canonify)(shroud, ctl->password, PASSWORDLEN);
1799 strcpy(shroud, ctl->password);
1801 ok = (protocol->getauth)(mailserver_socket, ctl, buf);
1804 if (ok == PS_LOCKBUSY)
1805 report(stderr, _("Lock-busy error on %s@%s\n"),
1807 ctl->server.truename);
1808 else if (ok == PS_AUTHFAIL)
1810 report(stderr, _("Authorization failure on %s@%s\n"),
1812 ctl->server.truename);
1815 * If we're running in background, try to mail the
1816 * calling user a heads-up about the authentication
1817 * failure once it looks like this isn't a fluke
1818 * due to the server being temporarily inaccessible.
1820 if (run.poll_interval
1821 && ctl->authfailcount++ > MAX_AUTHFAILS
1822 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1825 _("Subject: fetchmail authentication failed\r\n"));
1827 _("Fetchmail could not get mail from %s@%s.\r\n"),
1829 ctl->server.truename);
1831 _("The attempt to get authorization failed.\r\n" \
1832 "This probably means your password is invalid, but POP3 servers have\r\n" \
1833 "other failure modes that fetchmail cannot distinguish from this\r\n" \
1834 "because they don't send useful error messages on login failure.\r\n"));
1835 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1840 report(stderr, _("Unknown login or authentication error on %s@%s\n"),
1842 ctl->server.truename);
1848 ctl->errcount = fetches = 0;
1850 /* now iterate over each folder selected */
1851 for (idp = ctl->mailboxes; idp; idp = idp->next)
1858 /* reset timeout, in case we did an IDLE */
1859 mytimeout = ctl->server.timeout;
1861 if (outlevel >= O_DEBUG)
1864 report(stdout, _("selecting or re-polling folder %s\n"), idp->id);
1866 report(stdout, _("selecting or re-polling default folder\n"));
1869 /* compute # of messages and number of new messages waiting */
1870 stage = STAGE_GETRANGE;
1871 ok = (protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
1875 /* show user how many messages we downloaded */
1877 (void) sprintf(buf, _("%s at %s (folder %s)"),
1878 ctl->remotename, ctl->server.truename, idp->id);
1880 (void) sprintf(buf, _("%s at %s"),
1881 ctl->remotename, ctl->server.truename);
1882 if (outlevel > O_SILENT)
1884 if (count == -1) /* only used for ETRN */
1885 report(stdout, _("Polling %s\n"), ctl->server.truename);
1886 else if (count != 0)
1888 if (new != -1 && (count - new) > 0)
1889 report_build(stdout, _("%d %s (%d seen) for %s"),
1890 count, count > 1 ? _("messages") :
1894 report_build(stdout, _("%d %s for %s"),
1895 count, count > 1 ? _("messages") :
1898 report_complete(stdout, ".\n");
1900 report_complete(stdout, _(" (%d octets).\n"), bytes);
1904 /* these are pointless in normal daemon mode */
1905 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1906 report(stdout, _("No mail for %s\n"), buf);
1910 /* very important, this is where we leave the do loop */
1916 if (new == -1 || ctl->fetchall)
1918 fetches = new; /* set error status ccorrectly */
1920 * There used to be a `got noerror' here, but this
1921 * prevneted checking of multiple folders. This
1922 * comment is a reminder in case I introduced some
1923 * subtle bug by removing it...
1928 flag force_retrieval;
1931 * What forces this code is that in POP2 and
1932 * IMAP2bis you can't fetch a message without
1933 * having it marked `seen'. In POP3 and IMAP4, on the
1934 * other hand, you can (peek_capable is set by
1935 * each driver module to convey this; it's not a
1936 * method constant because of the difference between
1937 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1938 * if fetchall is on).
1940 * The result of being unable to peek is that if there's
1941 * any kind of transient error (DNS lookup failure, or
1942 * sendmail refusing delivery due to process-table limits)
1943 * the message will be marked "seen" on the server without
1944 * having been delivered. This is not a big problem if
1945 * fetchmail is running in foreground, because the user
1946 * will see a "skipped" message when it next runs and get
1949 * But in daemon mode this leads to the message
1950 * being silently ignored forever. This is not
1953 * We compensate for this by checking the error
1954 * count from the previous pass and forcing all
1955 * messages to be considered new if it's nonzero.
1957 force_retrieval = !peek_capable && (ctl->errcount > 0);
1960 * We need the size of each message before it's
1961 * loaded in order to pass it to the ESMTP SIZE
1962 * option. If the protocol has a getsizes method,
1963 * we presume this means it doesn't get reliable
1964 * sizes from message fetch responses.
1966 if (proto->getsizes)
1970 xalloca(msgsizes, int *, sizeof(int) * count);
1971 for (i = 0; i < count; i++)
1974 stage = STAGE_GETSIZES;
1975 ok = (proto->getsizes)(mailserver_socket, count, msgsizes);
1982 for (i = 0; i < count; i++)
1983 bytes += msgsizes[i];
1987 /* read, forward, and delete messages */
1988 stage = STAGE_FETCH;
1989 for (num = 1; num <= count; num++)
1991 flag toolarge = NUM_NONZERO(ctl->limit)
1992 && msgsizes && (msgsizes[num-1] > ctl->limit);
1993 flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(mailserver_socket,ctl,num));
1994 flag fetch_it = !toolarge
1995 && (ctl->fetchall || force_retrieval || !oldmsg);
1996 flag suppress_delete = FALSE;
1997 flag suppress_forward = FALSE;
1998 flag suppress_readbody = FALSE;
1999 flag retained = FALSE;
2002 * This check copes with Post Office/NT's
2003 * annoying habit of randomly prepending bogus
2004 * LIST items of length -1. Patrick Audley
2005 * <paudley@pobox.com> tells us: LIST shows a
2006 * size of -1, RETR and TOP return "-ERR
2007 * System error - couldn't open message", and
2008 * DELE succeeds but doesn't actually delete
2011 if (msgsizes && msgsizes[num-1] == -1)
2013 if (outlevel >= O_VERBOSE)
2015 _("Skipping message %d, length -1\n"),
2021 * We may want to reject this message if it's old
2022 * or oversized, and we're not forcing retrieval.
2026 if (outlevel > O_SILENT)
2028 report_build(stdout,
2029 _("skipping message %d (%d octets)"),
2030 num, msgsizes[num-1]);
2031 if (toolarge && !check_only)
2036 /* convert sz to string */
2037 sprintf(size, "%d", msgsizes[num-1]);
2039 /* build a list of skipped messages
2040 * val.id = size of msg (string cnvt)
2041 * val.status.num = warning_poll_count
2042 * val.status.mask = nbr of msg this size
2045 current = ctl->skipped;
2047 /* initialise warning_poll_count to the
2048 * current value so that all new msg will
2049 * be included in the next mail
2051 cnt = current? current->val.status.num : 0;
2053 /* if entry exists, increment the count */
2055 str_in_list(¤t, size, FALSE))
2058 current = current->next)
2060 if (strcmp(current->id, size) == 0)
2062 current->val.status.mark++;
2067 /* otherwise, create a new entry */
2068 /* initialise with current poll count */
2071 tmp = save_str(&ctl->skipped, size, 1);
2072 tmp->val.status.num = cnt;
2075 report_build(stdout, _(" (oversized, %d octets)"),
2082 flag wholesize = !protocol->fetch_body;
2084 /* request a message */
2085 ok = (protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
2089 /* -1 means we didn't see a size in the response */
2090 if (len == -1 && msgsizes)
2092 len = msgsizes[num - 1];
2096 if (outlevel > O_SILENT)
2098 report_build(stdout, _("reading message %d of %d"),
2102 report_build(stdout, _(" (%d %soctets)"),
2103 len, wholesize ? "" : _("header "));
2104 if (outlevel >= O_VERBOSE)
2105 report_complete(stdout, "\n");
2107 report_complete(stdout, " ");
2111 * Read the message headers and ship them to the
2114 ok = readheaders(mailserver_socket, len, msgsizes[num-1],
2116 if (ok == PS_RETAINED)
2117 suppress_forward = retained = TRUE;
2118 else if (ok == PS_TRANSIENT)
2119 suppress_delete = suppress_forward = TRUE;
2120 else if (ok == PS_REFUSED)
2121 suppress_forward = TRUE;
2122 else if (ok == PS_TRUNCATED)
2123 suppress_readbody = TRUE;
2128 * If we're using IMAP4 or something else that
2129 * can fetch headers separately from bodies,
2130 * it's time to request the body now. This
2131 * fetch may be skipped if we got an anti-spam
2132 * or other PS_REFUSED error response during
2135 if (protocol->fetch_body && !suppress_readbody)
2137 if (outlevel >= O_VERBOSE && !isafile(1))
2139 fputc('\n', stdout);
2143 if ((ok = (protocol->trail)(mailserver_socket, ctl, num)))
2146 if (!suppress_forward)
2148 if ((ok=(protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
2151 * Work around a bug in Novell's
2152 * broken GroupWise IMAP server;
2153 * its body FETCH response is missing
2154 * the required length for the data
2155 * string. This violates RFC2060.
2158 len = msgsizes[num-1] - msglen;
2159 if (outlevel > O_SILENT && !wholesize)
2160 report_complete(stdout,
2161 _(" (%d body octets) "), len);
2165 /* process the body now */
2168 if (suppress_readbody)
2170 /* When readheaders returns PS_TRUNCATED,
2171 the body (which has no content
2172 has already been read by readheaders,
2173 so we say readbody returned PS_SUCCESS */
2178 ok = readbody(mailserver_socket,
2183 if (ok == PS_TRANSIENT)
2184 suppress_delete = suppress_forward = TRUE;
2188 /* tell server we got it OK and resynchronize */
2189 if (protocol->trail)
2191 if (outlevel >= O_VERBOSE && !isafile(1))
2193 fputc('\n', stdout);
2197 ok = (protocol->trail)(mailserver_socket, ctl, num);
2203 /* count # messages forwarded on this pass */
2204 if (!suppress_forward)
2208 * Check to see if the numbers matched?
2210 * Yes, some servers foo this up horribly.
2211 * All IMAP servers seem to get it right, and
2212 * so does Eudora QPOP at least in 2.xx
2215 * Microsoft Exchange gets it completely
2216 * wrong, reporting compressed rather than
2217 * actual sizes (so the actual length of
2218 * message is longer than the reported size).
2219 * Another fine example of Microsoft brain death!
2221 * Some older POP servers, like the old UCB
2222 * POP server and the pre-QPOP QUALCOMM
2223 * versions, report a longer size in the LIST
2224 * response than actually gets shipped up.
2225 * It's unclear what is going on here, as the
2226 * QUALCOMM server (at least) seems to be
2227 * reporting the on-disk size correctly.
2229 if (msgsizes && msglen != msgsizes[num-1])
2231 if (outlevel >= O_DEBUG)
2233 _("message %d was not the expected length (%d actual != %d expected)\n"),
2234 num, msglen, msgsizes[num-1]);
2237 /* end-of-message processing starts here */
2238 if (!close_sink(ctl, &msgblk, !suppress_forward))
2241 suppress_delete = TRUE;
2247 * At this point in flow of control, either
2248 * we've bombed on a protocol error or had
2249 * delivery refused by the SMTP server
2250 * (unlikely -- I've never seen it) or we've
2251 * seen `accepted for delivery' and the
2252 * message is shipped. It's safe to mark the
2253 * message seen and delete it on the server
2257 /* tell the UID code we've seen this */
2262 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2263 if ((sdp->val.status.num == num)
2264 && (!toolarge || oldmsg))
2265 sdp->val.status.mark = UID_SEEN;
2268 /* maybe we delete this message now? */
2271 if (outlevel > O_SILENT)
2272 report(stdout, _(" retained\n"));
2274 else if (protocol->delete
2276 && (fetch_it ? !ctl->keep : ctl->flush))
2279 if (outlevel > O_SILENT)
2280 report_complete(stdout, _(" flushed\n"));
2281 ok = (protocol->delete)(mailserver_socket, ctl, num);
2285 delete_str(&ctl->newsaved, num);
2286 #endif /* POP3_ENABLE */
2288 else if (outlevel > O_SILENT)
2289 report_complete(stdout, _(" not flushed\n"));
2291 /* perhaps this as many as we're ready to handle */
2292 if (maxfetch && maxfetch <= fetches && fetches < count)
2294 report(stdout, _("fetchlimit %d reached; %d messages left on server\n"),
2295 maxfetch, count - fetches);
2301 if (!check_only && ctl->skipped
2302 && run.poll_interval > 0 && !nodetach)
2304 clean_skipped_list(&ctl->skipped);
2305 send_size_warnings(ctl);
2310 * Only re-poll if we either had some actual forwards and
2311 * either allowed deletions and had no errors.
2312 * Otherwise it is far too easy to get into infinite loops.
2314 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2318 /* ordinary termination with no errors -- officially log out */
2319 ok = (protocol->logout_cmd)(mailserver_socket, ctl);
2321 * Hmmmm...arguably this would be incorrect if we had fetches but
2322 * no dispatches (due to oversized messages, etc.)
2325 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2326 SockClose(mailserver_socket);
2330 /* we only get here on error */
2331 if (ok != 0 && ok != PS_SOCKET)
2333 stage = STAGE_LOGOUT;
2334 (protocol->logout_cmd)(mailserver_socket, ctl);
2336 SockClose(mailserver_socket);
2339 msg = (const char *)NULL; /* sacrifice to -Wall */
2346 msg = _("authorization");
2349 msg = _("missing or bad RFC822 header");
2355 msg = _("client/server synchronization");
2358 msg = _("client/server protocol");
2361 msg = _("lock busy on server");
2364 msg = _("SMTP transaction");
2367 msg = _("DNS lookup");
2370 report(stderr, _("undefined error\n"));
2373 /* no report on PS_MAXFETCH or PS_UNDEFINED */
2374 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2375 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2376 || ok==PS_LOCKBUSY || ok==PS_SMTP || ok==PS_DNS)
2377 report(stderr, _("%s error while fetching from %s\n"), msg, ctl->server.pollname);
2380 /* execute post-initialization command, if any */
2381 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2383 report(stderr, _("post-connection command failed with status %d\n"), ok);
2384 if (ok == PS_SUCCESS)
2388 signal(SIGALRM, alrmsave);
2389 signal(SIGPIPE, pipesave);
2393 int do_protocol(ctl, proto)
2394 /* retrieve messages from server using given protocol method table */
2395 struct query *ctl; /* parsed options with merged-in defaults */
2396 const struct method *proto; /* protocol method table */
2401 if (ctl->server.preauthenticate == A_KERBEROS_V4)
2403 report(stderr, _("Kerberos V4 support not linked.\n"));
2406 #endif /* KERBEROS_V4 */
2409 if (ctl->server.preauthenticate == A_KERBEROS_V5)
2411 report(stderr, _("Kerberos V5 support not linked.\n"));
2414 #endif /* KERBEROS_V5 */
2416 /* lacking methods, there are some options that may fail */
2419 /* check for unsupported options */
2422 _("Option --flush is not supported with %s\n"),
2426 else if (ctl->fetchall) {
2428 _("Option --all is not supported with %s\n"),
2433 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
2436 _("Option --limit is not supported with %s\n"),
2442 * If no expunge limit or we do expunges within the driver,
2443 * then just do one session, passing in any fetchlimit.
2445 if (proto->retry || !NUM_SPECIFIED(ctl->expunge))
2446 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
2448 * There's an expunge limit, and it isn't handled in the driver itself.
2449 * OK; do multiple sessions, each fetching a limited # of messages.
2450 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
2451 * (if it was nonzero).
2457 int expunge = NUM_VALUE_OUT(ctl->expunge);
2458 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
2461 ok = do_session(ctl, proto, expunge);
2462 totalcount += expunge;
2463 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
2465 if (ok != PS_LOCKBUSY)
2467 else if (lockouts >= MAX_LOCKOUTS)
2469 else /* ok == PS_LOCKBUSY */
2472 * Allow time for the server lock to release. if we
2473 * don't do this, we'll often hit a locked-mailbox
2474 * condition and fail.
2480 (ok == PS_MAXFETCH || ok == PS_LOCKBUSY);
2486 #if defined(HAVE_STDARG_H)
2487 void gen_send(int sock, const char *fmt, ... )
2489 void gen_send(sock, fmt, va_alist)
2490 int sock; /* socket to which server is connected */
2491 const char *fmt; /* printf-style format */
2494 /* assemble command in printf(3) style and send to the server */
2496 char buf [MSGBUFSIZE+1];
2499 if (protocol->tagged)
2500 (void) sprintf(buf, "%s ", GENSYM);
2504 #if defined(HAVE_STDARG_H)
2509 #ifdef HAVE_VSNPRINTF
2510 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2512 vsprintf(buf + strlen(buf), fmt, ap);
2516 strcat(buf, "\r\n");
2517 SockWrite(sock, buf, strlen(buf));
2519 if (outlevel >= O_MONITOR)
2523 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2527 sp = cp + strlen(shroud);
2533 buf[strlen(buf)-2] = '\0';
2534 report(stdout, "%s> %s\n", protocol->name, buf);
2538 int gen_recv(sock, buf, size)
2539 /* get one line of input from the server */
2540 int sock; /* socket to which server is connected */
2541 char *buf; /* buffer to receive input */
2542 int size; /* length of buffer */
2544 int oldphase = phase; /* we don't have to be re-entrant */
2546 phase = SERVER_WAIT;
2547 set_timeout(mytimeout);
2548 if (SockRead(sock, buf, size) == -1)
2557 if (buf[strlen(buf)-1] == '\n')
2558 buf[strlen(buf)-1] = '\0';
2559 if (buf[strlen(buf)-1] == '\r')
2560 buf[strlen(buf)-1] = '\0';
2561 if (outlevel >= O_MONITOR)
2562 report(stdout, "%s< %s\n", protocol->name, buf);
2568 #if defined(HAVE_STDARG_H)
2569 int gen_transact(int sock, const char *fmt, ... )
2571 int gen_transact(int sock, fmt, va_alist)
2572 int sock; /* socket to which server is connected */
2573 const char *fmt; /* printf-style format */
2576 /* assemble command in printf(3) style, send to server, accept a response */
2579 char buf [MSGBUFSIZE+1];
2581 int oldphase = phase; /* we don't have to be re-entrant */
2583 phase = SERVER_WAIT;
2585 if (protocol->tagged)
2586 (void) sprintf(buf, "%s ", GENSYM);
2590 #if defined(HAVE_STDARG_H)
2595 #ifdef HAVE_VSNPRINTF
2596 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2598 vsprintf(buf + strlen(buf), fmt, ap);
2602 strcat(buf, "\r\n");
2603 SockWrite(sock, buf, strlen(buf));
2605 if (outlevel >= O_MONITOR)
2609 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2613 sp = cp + strlen(shroud);
2619 buf[strlen(buf)-1] = '\0';
2620 report(stdout, "%s> %s\n", protocol->name, buf);
2623 /* we presume this does its own response echoing */
2624 ok = (protocol->parse_response)(sock, buf);
2630 /* driver.c ends here */