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_RES_SEARCH
37 #endif /* HAVE_RES_SEARCH */
41 #include <kerberosIV/des.h>
42 #include <kerberosIV/krb.h>
44 #if defined (__bsdi__)
45 #include <des.h> /* order of includes matters */
47 #define krb_get_err_text(e) (krb_err_txt[e])
49 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__linux__)
50 #define krb_get_err_text(e) (krb_err_txt[e])
56 #endif /* ! defined (__FreeBSD__) */
57 #endif /* ! defined (__bsdi__) */
58 #endif /* KERBEROS_V5 */
59 #include <netinet/in.h>
61 #endif /* KERBEROS_V4 */
65 #endif /* KERBEROS_V5 */
69 #include "fetchmail.h"
72 /* throw types for runtime errors */
73 #define THROW_TIMEOUT 1 /* server timed out */
74 #define THROW_SIGPIPE 2 /* SIGPIPE on stream socket */
76 #ifndef strstr /* glibc-2.1 declares this as a macro */
77 extern char *strstr(); /* needed on sysV68 R3V7.1. */
80 int batchcount; /* count of messages sent in current batch */
81 flag peek_capable; /* can we peek for better error recovery? */
82 int pass; /* how many times have we re-polled? */
83 int phase; /* where are we, for error-logging purposes? */
85 static const struct method *protocol;
86 static jmp_buf restart;
90 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
92 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
93 static int mytimeout; /* value of nonreponse timeout */
94 static int timeoutcount; /* count consecutive timeouts */
95 static int msglen; /* actual message length */
97 void set_timeout(int timeleft)
98 /* reset the nonresponse-timeout */
101 struct itimerval ntimeout;
106 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
107 ntimeout.it_value.tv_sec = timeleft;
108 ntimeout.it_value.tv_usec = 0;
109 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
113 static void timeout_handler (int signal)
114 /* handle SIGALRM signal indicating a server timeout */
117 longjmp(restart, THROW_TIMEOUT);
120 static void sigpipe_handler (int signal)
121 /* handle SIGPIPE signal indicating a broken stream socket */
123 longjmp(restart, THROW_SIGPIPE);
126 static int accept_count, reject_count;
128 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
129 /* add given name to xmit_names if it matches declared localnames */
130 /* name: name to map */
131 /* ctl: list of permissible aliases */
132 /* xmit_names: list of recipient names parsed out */
137 lname = idpair_find(&ctl->localnames, name+off);
138 if (!lname && ctl->wildcard)
141 if (lname != (char *)NULL)
143 if (outlevel >= O_DEBUG)
144 report(stdout, _("mapped %s to local %s\n"), name, lname);
145 save_str(xmit_names, lname, XMIT_ACCEPT);
150 static void find_server_names(const char *hdr,
152 struct idlist **xmit_names)
153 /* parse names out of a RFC822 header into an ID list */
154 /* hdr: RFC822 header in question */
155 /* ctl: list of permissible aliases */
156 /* xmit_names: list of recipient names parsed out */
158 if (hdr == (char *)NULL)
164 for (cp = nxtaddr(hdr);
171 * If the name of the user begins with a qmail virtual
172 * domain prefix, ignore the prefix. Doing this here
173 * means qvirtual will work either with ordinary name
174 * mapping or with a localdomains option.
176 if (ctl->server.qvirtual)
178 int sl = strlen(ctl->server.qvirtual);
180 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
184 if ((atsign = strchr(cp, '@'))) {
188 * Does a trailing segment of the hostname match something
189 * on the localdomains list? If so, save the whole name
192 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
195 rhs = atsign + (strlen(atsign) - strlen(idp->id));
197 (rhs[-1] == '.' || rhs[-1] == '@') &&
198 strcasecmp(rhs, idp->id) == 0)
200 if (outlevel >= O_DEBUG)
201 report(stdout, _("passed through %s matching %s\n"),
203 save_str(xmit_names, cp, XMIT_ACCEPT);
209 /* if we matched a local domain, idp != NULL */
213 * Check to see if the right-hand part is an alias
214 * or MX equivalent of the mailserver. If it's
215 * not, skip this name. If it is, we'll keep
216 * going and try to find a mapping to a client name.
218 if (!is_host_alias(atsign+1, ctl))
220 save_str(xmit_names, cp, XMIT_REJECT);
226 map_name(cp, ctl, xmit_names);
234 * Return zero on a syntactically invalid address, nz on a valid one.
236 * This used to be strchr(a, '.'), but it turns out that lines like this
238 * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
239 * id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
241 * are not uncommon. So now we just check that the following token is
242 * not itself an email address.
244 #define VALID_ADDRESS(a) !strchr(a, '@')
246 static char *parse_received(struct query *ctl, char *bufp)
247 /* try to extract real address from the Received line */
248 /* If a valid Received: line is found, we return the full address in
249 * a buffer which can be parsed from nxtaddr(). This is to ansure that
250 * the local domain part of the address can be passed along in
251 * find_server_names() if it contains one.
252 * Note: We should return a dummy header containing the address
253 * which makes nxtaddr() behave correctly.
256 char *base, *ok = (char *)NULL;
257 static char rbuf[HOSTLEN + USERNAMELEN + 4];
260 * Try to extract the real envelope addressee. We look here
261 * specifically for the mailserver's Received line.
262 * Note: this will only work for sendmail, or an MTA that
263 * shares sendmail's convention for embedding the envelope
264 * address in the Received line. Sendmail itself only
265 * does this when the mail has a single recipient.
267 if (outlevel >= O_DEBUG)
268 report(stdout, _("analyzing Received line:\n%s"), bufp);
270 /* search for whitepace-surrounded "by" followed by valid address */
271 for (base = bufp; ; base = ok + 2)
273 if (!(ok = strstr(base, "by")))
275 else if (!isspace(ok[-1]) || !isspace(ok[2]))
281 /* extract space-delimited token after "by" */
282 for (sp = ok + 2; isspace(*sp); sp++)
285 for (; !isspace(*sp); sp++)
289 /* look for valid address */
290 if (VALID_ADDRESS(rbuf))
293 ok = sp - 1; /* arrange to skip this token */
299 * If it's a DNS name of the mail server, look for the
300 * recipient name after a following "for". Otherwise
303 if (is_host_alias(rbuf, ctl))
305 if (outlevel >= O_DEBUG)
307 _("line accepted, %s is an alias of the mailserver\n"), rbuf);
311 if (outlevel >= O_DEBUG)
313 _("line rejected, %s is not an alias of the mailserver\n"),
318 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
319 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
321 if (!(ok = strstr(base, "for")))
323 else if (!isspace(ok[-1]) || !isspace(ok[3]))
329 /* extract space-delimited token after "for" */
330 for (sp = ok + 3; isspace(*sp); sp++)
333 for (; !isspace(*sp); sp++)
337 if (strchr(rbuf, '@'))
340 ok = sp - 1; /* arrange to skip this token */
345 flag want_gt = FALSE;
348 /* char after "for" could be space or a continuation newline */
349 for (sp = ok + 4; isspace(*sp); sp++)
352 *tp++ = ':'; /* Here is the hack. This is to be friends */
353 *tp++ = ' '; /* with nxtaddr()... */
359 while (*sp == '@') /* skip routes */
360 while (*sp && *sp++ != ':')
363 && (want_gt ? (*sp != '>') : !isspace(*sp))
369 /* uh oh -- whitespace here can't be right! */
375 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
383 if (outlevel >= O_DEBUG)
384 report(stdout, _("no Received address found\n"));
389 if (outlevel >= O_DEBUG) {
390 char *lf = rbuf + strlen(rbuf)-1;
392 if (outlevel >= O_DEBUG)
393 report(stdout, _("found Received address `%s'\n"), rbuf+2);
400 /* shared by readheaders and readbody */
401 static int sizeticker;
402 static struct msgblk msgblk;
404 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
406 static int readheaders(int sock,
411 /* read message headers and ship to SMTP or MDA */
412 /* sock: to which the server is connected */
413 /* fetchlen: length of message according to fetch response */
414 /* reallen: length of message according to getsizes */
415 /* ctl: query control record */
416 /* num: index of message */
421 struct addrblk *next;
423 struct addrblk *to_addrchain = NULL;
424 struct addrblk **to_chainptr = &to_addrchain;
425 struct addrblk *resent_to_addrchain = NULL;
426 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
428 char buf[MSGBUFSIZE+1];
429 int from_offs, reply_to_offs, resent_from_offs;
430 int app_from_offs, sender_offs, resent_sender_offs;
432 char *received_for, *rcv, *cp;
433 int n, linelen, oldlen, ch, remaining, skipcount;
435 flag no_local_matches = FALSE;
436 flag headers_ok, has_nuls;
437 int olderrs, good_addresses, bad_addresses;
440 has_nuls = headers_ok = FALSE;
441 msgblk.return_path[0] = '\0';
442 olderrs = ctl->errcount;
444 /* read message headers */
445 msgblk.reallen = reallen;
446 msgblk.headers = received_for = NULL;
447 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
448 sender_offs = resent_sender_offs = env_offs = -1;
454 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
458 line = xmalloc(sizeof(buf));
462 set_timeout(mytimeout);
463 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
466 free(msgblk.headers);
473 /* lines may not be properly CRLF terminated; fix this for qmail */
476 cp = buf + strlen(buf) - 1;
477 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
486 * Decode MIME encoded headers. We MUST do this before
487 * looking at the Content-Type / Content-Transfer-Encoding
488 * headers (RFC 2046).
493 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
497 /* check for end of headers */
501 has_nuls = (linelen != strlen(line));
503 goto process_headers;
507 * Check for end of message immediately. If one of your folders
508 * has been mangled, the delimiter may occur directly after the
511 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
514 has_nuls = (linelen != strlen(line));
515 goto process_headers;
518 /* check for RFC822 continuations */
519 set_timeout(mytimeout);
523 (ch == ' ' || ch == '\t'); /* continuation to next line? */
525 /* write the message size dots */
526 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
528 sizeticker += linelen;
529 while (sizeticker >= SIZETICKER)
536 sizeticker -= SIZETICKER;
540 /* we see an ordinary (non-header, non-message-delimiter line */
541 has_nuls = (linelen != strlen(line));
544 * When mail delivered to a multidrop mailbox on the server is
545 * addressed to multiple people on the client machine, there
546 * will be one copy left in the box for each recipient. Thus,
547 * if the mail is addressed to N people, each recipient will
550 * Foil this by suppressing all but one copy of a message with
551 * a given Message-ID. Note: This implementation only catches
552 * runs of successive identical messages, but that should be
555 * The accept_count test ensures that multiple pieces of identical
556 * email, each with a *single* addressee, won't be suppressed.
558 if (MULTIDROP(ctl) && accept_count > 1 && !strncasecmp(line, "Message-ID:", 11))
560 if (ctl->lastid && !strcasecmp(ctl->lastid, line))
566 ctl->lastid = strdup(line);
571 * The University of Washington IMAP server (the reference
572 * implementation of IMAP4 written by Mark Crispin) relies
573 * on being able to keep base-UID information in a special
574 * message at the head of the mailbox. This message should
575 * neither be deleted nor forwarded.
579 * We disable this check under POP2 because there's no way to
580 * prevent deletion of the message. So at least we ought to
581 * forward it to the user so he or she will have some clue
582 * that things have gone awry.
584 if (protocol->port != 109)
585 #endif /* POP2_ENABLE */
586 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
588 free(msgblk.headers);
593 * This code prevents fetchmail from becoming an accessory after
594 * the fact to upstream sendmails with the `E' option on. It also
595 * copes with certain brain-dead POP servers (like NT's) that pass
596 * through Unix from_ lines.
598 * Either of these bugs can result in a non-RFC822 line at the
599 * beginning of the headers. If fetchmail just passes it
600 * through, the client listener may think the message has *no*
601 * headers (since the first) line it sees doesn't look
602 * RFC822-conformant) and fake up a set.
604 * What the user would see in this case is bogus (synthesized)
605 * headers, followed by a blank line, followed by the >From,
606 * followed by the real headers, followed by a blank line,
609 * We forestall this lossage by tossing anything that looks
610 * like an escaped or passed-through From_ line in headers.
611 * These aren't RFC822 so our conscience is clear...
613 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
620 * If we see a Status line, it may have been inserted by an MUA
621 * on the mail host, or it may have been inserted by the server
622 * program after the headers in the transaction stream. This
623 * can actually hose some new-mail notifiers such as xbuffy,
624 * which assumes any Status line came from a *local* MDA and
625 * therefore indicates that the message has been seen.
627 * Some buggy POP servers (including at least the 3.3(20)
628 * version of the one distributed with IMAP) insert empty
629 * Status lines in the transaction stream; we'll chuck those
630 * unconditionally. Nonempty ones get chucked if the user
631 * turns on the dropstatus flag.
636 if (!strncasecmp(line, "Status:", 7))
638 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
643 while (*cp && isspace(*cp)) cp++;
644 if (!*cp || ctl->dropstatus)
653 line = reply_hack(line, ctl->server.truename);
656 * OK, this is messy. If we're forwarding by SMTP, it's the
657 * SMTP-receiver's job (according to RFC821, page 22, section
658 * 4.1.1) to generate a Return-Path line on final delivery.
659 * The trouble is, we've already got one because the
660 * mailserver's SMTP thought *it* was responsible for final
663 * Stash away the contents of Return-Path (as modified by reply_hack)
664 * for use in generating MAIL FROM later on, then prevent the header
665 * from being saved with the others. In effect, we strip it off here.
667 * If the SMTP server conforms to the standards, and fetchmail gets the
668 * envelope sender from the Return-Path, the new Return-Path should be
669 * exactly the same as the original one.
671 * We do *not* want to ignore empty Return-Path headers. These should
672 * be passed through as a way of indicating that a message should
673 * not trigger bounces if delivery fails. What we *do* need to do is
674 * make sure we never try to rewrite such a blank Return-Path. We
675 * handle this with a check for <> in the rewrite logic above.
677 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
679 strcpy(msgblk.return_path, cp);
688 oldlen = strlen(line);
689 msgblk.headers = xmalloc(oldlen + 1);
690 (void) strcpy(msgblk.headers, line);
692 line = msgblk.headers;
698 newlen = oldlen + strlen(line);
699 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
700 if (msgblk.headers == NULL) {
704 strcpy(msgblk.headers + oldlen, line);
706 line = msgblk.headers + oldlen;
710 if (!strncasecmp("From:", line, 5))
711 from_offs = (line - msgblk.headers);
712 else if (!strncasecmp("Reply-To:", line, 9))
713 reply_to_offs = (line - msgblk.headers);
714 else if (!strncasecmp("Resent-From:", line, 12))
715 resent_from_offs = (line - msgblk.headers);
716 else if (!strncasecmp("Apparently-From:", line, 16))
717 app_from_offs = (line - msgblk.headers);
718 else if (!strncasecmp("Sender:", line, 7))
719 sender_offs = (line - msgblk.headers);
720 else if (!strncasecmp("Resent-Sender:", line, 14))
721 resent_sender_offs = (line - msgblk.headers);
723 else if (!strncasecmp("Message-Id:", buf, 11))
725 if (ctl->server.uidl)
729 buf[IDLEN+12] = 0; /* prevent stack overflow */
730 sscanf(buf+12, "%s", id);
731 if (!str_find( &ctl->newsaved, num))
733 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
734 new->val.status.num = num;
739 else if (!MULTIDROP(ctl))
742 else if (!strncasecmp("To:", line, 3)
743 || !strncasecmp("Cc:", line, 3)
744 || !strncasecmp("Bcc:", line, 4)
745 || !strncasecmp("Apparently-To:", line, 14))
747 *to_chainptr = xmalloc(sizeof(struct addrblk));
748 (*to_chainptr)->offset = (line - msgblk.headers);
749 to_chainptr = &(*to_chainptr)->next;
753 else if (!strncasecmp("Resent-To:", line, 10)
754 || !strncasecmp("Resent-Cc:", line, 10)
755 || !strncasecmp("Resent-Bcc:", line, 11))
757 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
758 (*resent_to_chainptr)->offset = (line - msgblk.headers);
759 resent_to_chainptr = &(*resent_to_chainptr)->next;
760 *resent_to_chainptr = NULL;
763 else if (ctl->server.envelope != STRING_DISABLED)
765 if (ctl->server.envelope
766 && strcasecmp(ctl->server.envelope, "Received"))
768 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
770 strlen(ctl->server.envelope)))
772 if (skipcount++ != ctl->server.envskip)
774 env_offs = (line - msgblk.headers);
777 else if (!received_for && !strncasecmp("Received:", line, 9))
779 if (skipcount++ != ctl->server.envskip)
781 received_for = parse_received(ctl, line);
788 * We want to detect this early in case there are so few headers that the
789 * dispatch logic barfs.
793 if (outlevel > O_SILENT)
795 _("message delimiter found while scanning headers\n"));
799 * Hack time. If the first line of the message was blank, with no headers
800 * (this happens occasionally due to bad gatewaying software) cons up
801 * a set of fake headers.
803 * If you modify the fake header template below, be sure you don't
804 * make either From or To address @-less, otherwise the reply_hack
805 * logic will do bad things.
807 if (msgblk.headers == (char *)NULL)
810 snprintf(buf, sizeof(buf),
813 #endif /* HAVE_SNPRINTF */
814 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
815 user, fetchmailhost, ctl->remotename, ctl->server.truename);
816 msgblk.headers = xstrdup(buf);
820 * We can now process message headers before reading the text.
821 * In fact we have to, as this will tell us where to forward to.
824 /* Check for MIME headers indicating possible 8-bit data */
825 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
828 if (ctl->server.sdps && sdps_envfrom)
830 /* We have the real envelope return-path, stored out of band by
831 * SDPS - that's more accurate than any header is going to be.
833 strcpy(msgblk.return_path, sdps_envfrom);
836 #endif /* SDPS_ENABLE */
838 * If there is a Return-Path address on the message, this was
839 * almost certainly the MAIL FROM address given the originating
840 * sendmail. This is the best thing to use for logging the
841 * message origin (it sets up the right behavior for bounces and
842 * mailing lists). Otherwise, fall down to the next available
843 * envelope address (which is the most probable real sender).
844 * *** The order is important! ***
845 * This is especially useful when receiving mailing list
846 * messages in multidrop mode. if a local address doesn't
847 * exist, the bounce message won't be returned blindly to the
848 * author or to the list itself but rather to the list manager
849 * (ex: specified by "Sender:") which is much less annoying. This
850 * is true for most mailing list packages.
852 if( !msgblk.return_path[0] ){
854 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
855 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
856 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
857 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
858 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
859 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
860 if (ap) strcpy( msgblk.return_path, ap );
863 /* cons up a list of local recipients */
864 msgblk.recipients = (struct idlist *)NULL;
865 accept_count = reject_count = 0;
866 /* is this a multidrop box? */
870 if (ctl->server.sdps && sdps_envto)
872 /* We have the real envelope recipient, stored out of band by
873 * SDPS - that's more accurate than any header is going to be.
875 find_server_names(sdps_envto, ctl, &msgblk.recipients);
878 #endif /* SDPS_ENABLE */
879 if (env_offs > -1) /* We have the actual envelope addressee */
880 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
881 else if (received_for)
883 * We have the Received for addressee.
884 * It has to be a mailserver address, or we
885 * wouldn't have got here.
886 * We use find_server_names() to let local
887 * hostnames go through.
889 find_server_names(received_for, ctl, &msgblk.recipients);
893 * We haven't extracted the envelope address.
894 * So check all the "Resent-To" header addresses if
895 * they exist. If and only if they don't, consider
898 register struct addrblk *nextptr;
899 if (resent_to_addrchain) {
900 /* delete the "To" chain and substitute it
901 * with the "Resent-To" list
903 while (to_addrchain) {
904 nextptr = to_addrchain->next;
906 to_addrchain = nextptr;
908 to_addrchain = resent_to_addrchain;
909 resent_to_addrchain = NULL;
911 /* now look for remaining adresses */
912 while (to_addrchain) {
913 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
914 nextptr = to_addrchain->next;
916 to_addrchain = nextptr;
921 no_local_matches = TRUE;
922 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
923 if (outlevel >= O_DEBUG)
925 _("no local matches, forwarding to %s\n"),
929 else /* it's a single-drop box, use first localname */
930 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
934 * Time to either address the message or decide we can't deliver it yet.
936 if (ctl->errcount > olderrs) /* there were DNS errors above */
938 if (outlevel >= O_DEBUG)
940 _("forwarding and deletion suppressed due to DNS errors\n"));
941 free(msgblk.headers);
942 free_str_list(&msgblk.recipients);
943 return(PS_TRANSIENT);
947 /* set up stuffline() so we can deliver the message body through it */
948 if ((n = open_sink(ctl, &msgblk,
949 &good_addresses, &bad_addresses)) != PS_SUCCESS)
951 free(msgblk.headers);
952 free_str_list(&msgblk.recipients);
959 * Some server/sendmail combinations cause problems when our
960 * synthetic Received line is before the From header. Cope
963 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
964 rcv = msgblk.headers;
965 /* handle ">Received:" lines too */
966 while (rcv > msgblk.headers && rcv[-1] != '\n')
968 if (rcv > msgblk.headers)
973 n = stuffline(ctl, msgblk.headers);
976 if (!run.invisible && n != -1)
978 /* utter any per-message Received information we need here */
979 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
980 n = stuffline(ctl, buf);
984 * This header is technically invalid under RFC822.
985 * POP3, IMAP, etc. are not legal mail-parameter values.
987 * We used to include ctl->remotename in this log line,
988 * but this can be secure information that would be bad
991 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
995 n = stuffline(ctl, buf);
999 if (good_addresses == 0)
1002 "for %s@%s (by default); ",
1003 user, ctl->destaddr);
1005 else if (good_addresses == 1)
1007 for (idp = msgblk.recipients; idp; idp = idp->next)
1008 if (idp->val.status.mark == XMIT_ACCEPT)
1009 break; /* only report first address */
1010 if (strchr(idp->id, '@'))
1011 sprintf(buf+1, "for %s", idp->id);
1014 * This could be a bit misleading, as destaddr is
1015 * the forwarding host rather than the actual
1016 * destination. Most of the time they coincide.
1018 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
1019 sprintf(buf+strlen(buf), " (%s); ",
1020 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
1025 strcat(buf, rfc822timestamp());
1026 strcat(buf, "\r\n");
1027 n = stuffline(ctl, buf);
1033 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
1037 report(stdout, _("writing RFC822 msgblk.headers\n"));
1039 free(msgblk.headers);
1040 free_str_list(&msgblk.recipients);
1043 else if (!run.use_syslog && outlevel >= O_VERBOSE)
1046 /* write error notifications */
1047 if (no_local_matches || has_nuls || bad_addresses)
1050 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
1053 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
1054 if (no_local_matches)
1056 if (reject_count != 1)
1057 strcat(errhd, _("no recipient addresses matched declared local names"));
1060 for (idp = msgblk.recipients; idp; idp = idp->next)
1061 if (idp->val.status.mark == XMIT_REJECT)
1063 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1069 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1070 strcat(errhd, "; ");
1071 strcat(errhd, _("message has embedded NULs"));
1076 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1077 strcat(errhd, "; ");
1078 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1079 errlen = strlen(errhd);
1080 for (idp = msgblk.recipients; idp; idp = idp->next)
1081 if (idp->val.status.mark == XMIT_RCPTBAD)
1082 errlen += strlen(idp->id) + 2;
1084 xalloca(errmsg, char *, errlen+3);
1085 (void) strcpy(errmsg, errhd);
1086 for (idp = msgblk.recipients; idp; idp = idp->next)
1087 if (idp->val.status.mark == XMIT_RCPTBAD)
1089 strcat(errmsg, idp->id);
1091 strcat(errmsg, ", ");
1096 strcat(errmsg, "\r\n");
1098 /* ship out the error line */
1099 stuffline(ctl, errmsg);
1102 /* issue the delimiter line */
1107 stuffline(ctl, buf);
1109 free(msgblk.headers);
1110 free_str_list(&msgblk.recipients);
1111 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1114 static int readbody(int sock, struct query *ctl, flag forward, int len)
1115 /* read and dispose of a message body presented on sock */
1116 /* ctl: query control record */
1117 /* sock: to which the server is connected */
1118 /* len: length of message */
1119 /* forward: TRUE to forward */
1122 unsigned char buf[MSGBUFSIZE+4];
1123 unsigned char *inbufp = buf;
1124 flag issoftline = FALSE;
1127 * Pass through the text lines in the body.
1129 * Yes, this wants to be ||, not &&. The problem is that in the most
1130 * important delimited protocol, POP3, the length is not reliable.
1131 * As usual, the problem is Microsoft brain damage; see FAQ item S2.
1132 * So, for delimited protocols we need to ignore the length here and
1133 * instead drop out of the loop with a break statement when we see
1134 * the message delimiter.
1136 while (protocol->delimited || len > 0)
1138 set_timeout(mytimeout);
1139 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1147 /* write the message size dots */
1150 sizeticker += linelen;
1151 while (sizeticker >= SIZETICKER)
1153 if (!run.use_syslog && outlevel > O_SILENT)
1158 sizeticker -= SIZETICKER;
1163 /* check for end of message */
1164 if (protocol->delimited && *inbufp == '.')
1166 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1168 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1171 msglen--; /* subtract the size of the dot escape */
1176 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1177 issoftline = UnMimeBodyline(&inbufp, protocol->delimited, issoftline);
1178 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1181 * Soft linebreak, but less than 200 bytes left in
1182 * input buffer. Rather than doing a buffer overrun,
1183 * ignore the soft linebreak, NL-terminate data and
1184 * deliver what we have now.
1185 * (Who writes lines longer than 2K anyway?)
1187 *inbufp = '\n'; *(inbufp+1) = '\0';
1192 /* ship out the text line */
1193 if (forward && (!issoftline))
1198 /* guard against very long lines */
1199 buf[MSGBUFSIZE+1] = '\r';
1200 buf[MSGBUFSIZE+2] = '\n';
1201 buf[MSGBUFSIZE+3] = '\0';
1203 n = stuffline(ctl, buf);
1207 report(stdout, _("writing message text\n"));
1211 else if (outlevel >= O_VERBOSE)
1221 kerberos_auth (socket, canonical)
1222 /* authenticate to the server host using Kerberos V4 */
1223 int socket; /* socket to server host */
1224 #if defined(__FreeBSD__) || defined(__OpenBSD__)
1225 char *canonical; /* server name */
1227 const char *canonical; /* server name */
1230 char * host_primary;
1234 Key_schedule schedule;
1237 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1238 rem = (krb_sendauth (0L, socket, ticket, "pop",
1240 ((char *) (krb_realmofhost (canonical))),
1241 ((unsigned long) 0),
1245 ((struct sockaddr_in *) 0),
1246 ((struct sockaddr_in *) 0),
1248 if (rem != KSUCCESS)
1250 report(stderr, _("kerberos error %s\n"), (krb_get_err_text (rem)));
1251 return (PS_AUTHFAIL);
1255 #endif /* KERBEROS_V4 */
1258 static int kerberos5_auth(socket, canonical)
1259 /* authenticate to the server host using Kerberos V5 */
1260 int socket; /* socket to server host */
1261 const char *canonical; /* server name */
1263 krb5_error_code retval;
1264 krb5_context context;
1266 krb5_principal client = NULL, server = NULL;
1267 krb5_error *err_ret = NULL;
1269 krb5_auth_context auth_context = NULL;
1271 krb5_init_context(&context);
1272 krb5_init_ets(context);
1273 krb5_auth_con_init(context, &auth_context);
1275 if (retval = krb5_cc_default(context, &ccdef)) {
1276 report(stderr, "krb5_cc_default: %s\n", error_message(retval));
1280 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1281 report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
1285 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1288 report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
1292 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1293 "KPOPV1.0", client, server,
1294 AP_OPTS_MUTUAL_REQUIRED,
1295 NULL, /* no data to checksum */
1296 0, /* no creds, use ccache instead */
1300 NULL); /* don't need reply */
1302 krb5_free_principal(context, server);
1303 krb5_free_principal(context, client);
1304 krb5_auth_con_free(context, auth_context);
1308 if (err_ret && err_ret->e_text) {
1309 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1310 error_message(retval),
1313 if (err_ret && err_ret->text.length) {
1314 report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
1315 error_message(retval),
1316 err_ret->text.length,
1317 err_ret->text.data);
1319 krb5_free_error(context, err_ret);
1321 report(stderr, "krb5_sendauth: %s\n", error_message(retval));
1327 #endif /* KERBEROS_V5 */
1329 static void clean_skipped_list(struct idlist **skipped_list)
1330 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1332 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1333 prev = current = head = *skipped_list;
1339 /* if item has no reference, remove it */
1340 if (current && current->val.status.mark == 0)
1342 if (current == head) /* remove first item (head) */
1344 head = current->next;
1345 if (current->id) free(current->id);
1347 prev = current = head;
1349 else /* remove middle/last item */
1351 tmp = current->next;
1353 if (current->id) free(current->id);
1358 else /* skip this item */
1361 current = current->next;
1365 *skipped_list = head;
1368 static void send_size_warnings(struct query *ctl)
1369 /* send warning mail with skipped msg; reset msg count when user notified */
1372 int msg_to_send = FALSE;
1373 struct idlist *head=NULL, *current=NULL;
1374 int max_warning_poll_count;
1375 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server %s:"
1377 head = ctl->skipped;
1381 /* don't start a notification message unless we need to */
1382 for (current = head; current; current = current->next)
1383 if (current->val.status.num == 0 && current->val.status.mark)
1389 * There's no good way to recover if we can't send notification mail,
1390 * but it's not a disaster, either, since the skipped mail will not
1393 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1395 stuff_warning(ctl, OVERHD, ctl->server.pollname);
1397 if (run.poll_interval == 0)
1398 max_warning_poll_count = 0;
1400 max_warning_poll_count = ctl->warnings/run.poll_interval;
1402 /* parse list of skipped msg, adding items to the mail */
1403 for (current = head; current; current = current->next)
1405 if (current->val.status.num == 0 && current->val.status.mark)
1407 nbr = current->val.status.mark;
1408 size = atoi(current->id);
1410 _("\t%d msg %d octets long skipped by fetchmail.\n"),
1413 current->val.status.num++;
1414 current->val.status.mark = 0;
1416 if (current->val.status.num >= max_warning_poll_count)
1417 current->val.status.num = 0;
1420 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1424 static int do_session(ctl, proto, maxfetch)
1425 /* retrieve messages from server using given protocol method table */
1426 struct query *ctl; /* parsed options with merged-in defaults */
1427 const struct method *proto; /* protocol method table */
1428 const int maxfetch; /* maximum number of messages to fetch */
1431 #ifdef HAVE_VOLATILE
1432 volatile int ok, mailserver_socket = -1; /* pacifies -Wall */
1434 int ok, mailserver_socket = -1;
1435 #endif /* HAVE_VOLATILE */
1437 void (*pipesave)(int);
1438 void (*alrmsave)(int);
1439 struct idlist *current=NULL, *tmp=NULL;
1442 ctl->server.base_protocol = protocol;
1446 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1449 /* set up the server-nonresponse timeout */
1450 alrmsave = signal(SIGALRM, timeout_handler);
1451 mytimeout = ctl->server.timeout;
1453 /* set up the broken-pipe timeout */
1454 pipesave = signal(SIGPIPE, sigpipe_handler);
1456 if ((js = setjmp(restart)))
1458 #ifdef HAVE_SIGPROCMASK
1460 * Don't rely on setjmp() to restore the blocked-signal mask.
1461 * It does this under BSD but is required not to under POSIX.
1463 * If your Unix doesn't have sigprocmask, better hope it has
1464 * BSD-like behavior. Otherwise you may see fetchmail get
1465 * permanently wedged after a second timeout on a bad read,
1466 * because alarm signals were blocked after the first.
1470 sigfillset(&allsigs);
1471 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1472 #endif /* HAVE_SIGPROCMASK */
1474 if (js == THROW_SIGPIPE)
1477 _("SIGPIPE thrown from an MDA or a stream socket error"));
1480 else if (js == THROW_TIMEOUT)
1482 if (phase == OPEN_WAIT)
1484 _("timeout after %d seconds waiting to connect to server %s.\n"),
1485 ctl->server.timeout, ctl->server.pollname);
1486 else if (phase == SERVER_WAIT)
1488 _("timeout after %d seconds waiting for server %s.\n"),
1489 ctl->server.timeout, ctl->server.pollname);
1490 else if (phase == FORWARDING_WAIT)
1492 _("timeout after %d seconds waiting for %s.\n"),
1493 ctl->server.timeout,
1494 ctl->mda ? "MDA" : "SMTP");
1495 else if (phase == LISTENER_WAIT)
1497 _("timeout after %d seconds waiting for listener to respond.\n"));
1500 _("timeout after %d seconds.\n"), ctl->server.timeout);
1503 * If we've exceeded our threshold for consecutive timeouts,
1504 * try to notify the user, then mark the connection wedged.
1506 if (timeoutcount > MAX_TIMEOUTS
1507 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1510 _("Subject: fetchmail sees repeated timeouts\r\n"));
1512 _("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
1515 ctl->server.truename);
1517 _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1519 _("is wedged, or that your mailbox file on the server has been corrupted by"));
1521 _("a server error. You can run `fetchmail -v -v' to diagnose the problem."));
1523 _("Fetchmail won't poll this mailbox again until you restart it."));
1524 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1531 /* try to clean up all streams */
1533 if (ctl->smtp_socket != -1)
1534 close(ctl->smtp_socket);
1535 if (mailserver_socket != -1)
1536 SockClose(mailserver_socket);
1540 char buf[POPBUFSIZE+1], *realhost;
1541 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1543 int fetches, dispatches, oldphase;
1544 #else /* INET6_ENABLE */
1545 int port, fetches, dispatches, oldphase;
1546 #endif /* INET6_ENABLE */
1549 /* execute pre-initialization command, if any */
1550 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1553 _("pre-connection command failed with status %d\n"), ok);
1558 /* open a socket to the mail server */
1561 set_timeout(mytimeout);
1564 port = ctl->server.port ? ctl->server.port : ( ctl->use_ssl ? protocol->sslport : protocol->port );
1566 port = ctl->server.port ? ctl->server.port : protocol->port;
1568 #endif /* !INET6_ENABLE */
1569 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1571 /* allow time for the port to be set up if we have a plugin */
1572 if (ctl->server.plugin)
1575 if ((mailserver_socket = SockOpen(realhost,
1576 ctl->server.service ? ctl->server.service : protocol->service,
1577 ctl->server.netsec, ctl->server.plugin)) == -1)
1578 #else /* INET6_ENABLE */
1579 if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1580 #endif /* INET6_ENABLE */
1584 #ifdef HAVE_RES_SEARCH
1585 if (err_no != 0 && h_errno != 0)
1586 report(stderr, _("fetchmail: internal inconsistency\n"));
1589 * Avoid generating a bogus error every poll cycle when we're
1590 * in daemon mode but the connection to the outside world
1593 if (err_no == EHOSTUNREACH && run.poll_interval)
1596 report_build(stderr, _("fetchmail: %s connection to %s failed"),
1597 protocol->name, ctl->server.pollname);
1598 #ifdef HAVE_RES_SEARCH
1601 if (h_errno == HOST_NOT_FOUND)
1602 report_complete(stderr, _(": host is unknown\n"));
1603 else if (h_errno == NO_ADDRESS)
1604 report_complete(stderr, _(": name is valid but has no IP address\n"));
1605 else if (h_errno == NO_RECOVERY)
1606 report_complete(stderr, _(": unrecoverable name server error\n"));
1607 else if (h_errno == TRY_AGAIN)
1608 report_complete(stderr, _(": temporary name server error\n"));
1610 report_complete(stderr, _(": unknown DNS error %d\n"), h_errno);
1613 #endif /* HAVE_RES_SEARCH */
1614 report_complete(stderr, ": %s\n", strerror(err_no));
1617 #endif /* INET6_ENABLE */
1627 /* perform initial SSL handshake on open connection */
1628 /* Note: We pass the realhost name over for certificate
1629 verification. We may want to make this configurable */
1630 if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslkey,ctl->sslcert,realhost) == -1)
1632 report(stderr, "SSL connection failed.");
1638 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1640 set_timeout(mytimeout);
1641 ok = kerberos_auth(mailserver_socket, ctl->server.truename);
1646 #endif /* KERBEROS_V4 */
1649 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1651 set_timeout(mytimeout);
1652 ok = kerberos5_auth(mailserver_socket, ctl->server.truename);
1657 #endif /* KERBEROS_V5 */
1659 /* accept greeting message from mail server */
1660 ok = (protocol->parse_response)(mailserver_socket, buf);
1664 /* try to get authorized to fetch mail */
1665 if (protocol->getauth)
1667 if (protocol->password_canonify)
1668 (protocol->password_canonify)(shroud, ctl->password, PASSWORDLEN);
1670 strcpy(shroud, ctl->password);
1672 ok = (protocol->getauth)(mailserver_socket, ctl, buf);
1675 if (ok == PS_LOCKBUSY)
1676 report(stderr, _("Lock-busy error on %s@%s\n"),
1678 ctl->server.truename);
1683 report(stderr, _("Authorization failure on %s@%s\n"),
1685 ctl->server.truename);
1688 * If we're running in background, try to mail the
1689 * calling user a heads-up about the authentication
1690 * failure once it looks like this isn't a fluke
1691 * due to the server being temporarily inaccessible.
1693 if (run.poll_interval
1694 && ctl->authfailcount++ > MAX_AUTHFAILS
1695 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1698 _("Subject: fetchmail authentication failed\r\n"));
1700 _("Fetchmail could not get mail from %s@%s."),
1702 ctl->server.truename);
1704 _("The attempt to get authorization failed."));
1706 _("This probably means your password is invalid."));
1707 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1715 ctl->errcount = fetches = 0;
1717 /* now iterate over each folder selected */
1718 for (idp = ctl->mailboxes; idp; idp = idp->next)
1725 if (outlevel >= O_DEBUG)
1728 report(stdout, _("selecting or re-polling folder %s\n"), idp->id);
1730 report(stdout, _("selecting or re-polling default folder\n"));
1733 /* compute # of messages and number of new messages waiting */
1734 ok = (protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
1738 /* show user how many messages we downloaded */
1740 (void) sprintf(buf, _("%s at %s (folder %s)"),
1741 ctl->remotename, ctl->server.truename, idp->id);
1743 (void) sprintf(buf, _("%s at %s"),
1744 ctl->remotename, ctl->server.truename);
1745 if (outlevel > O_SILENT)
1747 if (count == -1) /* only used for ETRN */
1748 report(stdout, _("Polling %s\n"), ctl->server.truename);
1749 else if (count != 0)
1751 if (new != -1 && (count - new) > 0)
1752 report_build(stdout, _("%d %s (%d seen) for %s"),
1753 count, count > 1 ? _("messages") :
1757 report_build(stdout, _("%d %s for %s"),
1758 count, count > 1 ? _("messages") :
1761 report_complete(stdout, ".\n");
1763 report_complete(stdout, _(" (%d octets).\n"), bytes);
1767 /* these are pointless in normal daemon mode */
1768 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1769 report(stdout, _("No mail for %s\n"), buf);
1773 /* very important, this is where we leave the do loop */
1779 if (new == -1 || ctl->fetchall)
1781 fetches = new; /* set error status ccorrectly */
1786 flag force_retrieval;
1789 * What forces this code is that in POP2 and
1790 * IMAP2bis you can't fetch a message without
1791 * having it marked `seen'. In POP3 and IMAP4, on the
1792 * other hand, you can (peek_capable is set by
1793 * each driver module to convey this; it's not a
1794 * method constant because of the difference between
1795 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1796 * if fetchall is on).
1798 * The result of being unable to peek is that if there's
1799 * any kind of transient error (DNS lookup failure, or
1800 * sendmail refusing delivery due to process-table limits)
1801 * the message will be marked "seen" on the server without
1802 * having been delivered. This is not a big problem if
1803 * fetchmail is running in foreground, because the user
1804 * will see a "skipped" message when it next runs and get
1807 * But in daemon mode this leads to the message
1808 * being silently ignored forever. This is not
1811 * We compensate for this by checking the error
1812 * count from the previous pass and forcing all
1813 * messages to be considered new if it's nonzero.
1815 force_retrieval = !peek_capable && (ctl->errcount > 0);
1818 * We need the size of each message before it's
1819 * loaded in order to pass it to the ESMTP SIZE
1820 * option. If the protocol has a getsizes method,
1821 * we presume this means it doesn't get reliable
1822 * sizes from message fetch responses.
1824 if (proto->getsizes)
1828 xalloca(msgsizes, int *, sizeof(int) * count);
1829 for (i = 0; i < count; i++)
1832 ok = (proto->getsizes)(mailserver_socket, count, msgsizes);
1839 for (i = 0; i < count; i++)
1840 bytes += msgsizes[i];
1844 /* read, forward, and delete messages */
1845 for (num = 1; num <= count; num++)
1847 flag toolarge = NUM_NONZERO(ctl->limit)
1848 && msgsizes && (msgsizes[num-1] > ctl->limit);
1849 flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(mailserver_socket,ctl,num));
1850 flag fetch_it = !toolarge
1851 && (ctl->fetchall || force_retrieval || !oldmsg);
1852 flag suppress_delete = FALSE;
1853 flag suppress_forward = FALSE;
1854 flag suppress_readbody = FALSE;
1855 flag retained = FALSE;
1858 * This check copes with Post Office/NT's
1859 * annoying habit of randomly prepending bogus
1860 * LIST items of length -1. Patrick Audley
1861 * <paudley@pobox.com> tells us: LIST shows a
1862 * size of -1, RETR and TOP return "-ERR
1863 * System error - couldn't open message", and
1864 * DELE succeeds but doesn't actually delete
1867 if (msgsizes && msgsizes[num-1] == -1)
1869 if (outlevel >= O_VERBOSE)
1871 _("Skipping message %d, length -1\n"),
1877 * We may want to reject this message if it's old
1878 * or oversized, and we're not forcing retrieval.
1882 if (outlevel > O_SILENT)
1884 report_build(stdout, _("skipping message %d"), num);
1885 if (toolarge && !check_only)
1890 /* convert sz to string */
1891 sprintf(size, "%d", msgsizes[num-1]);
1893 /* build a list of skipped messages
1894 * val.id = size of msg (string cnvt)
1895 * val.status.num = warning_poll_count
1896 * val.status.mask = nbr of msg this size
1899 current = ctl->skipped;
1901 /* initialise warning_poll_count to the
1902 * current value so that all new msg will
1903 * be included in the next mail
1905 cnt = current? current->val.status.num : 0;
1907 /* if entry exists, increment the count */
1909 str_in_list(¤t, size, FALSE))
1912 current = current->next)
1914 if (strcmp(current->id, size) == 0)
1916 current->val.status.mark++;
1921 /* otherwise, create a new entry */
1922 /* initialise with current poll count */
1925 tmp = save_str(&ctl->skipped, size, 1);
1926 tmp->val.status.num = cnt;
1929 report_build(stdout, _(" (oversized, %d octets)"),
1936 flag wholesize = !protocol->fetch_body;
1938 /* request a message */
1939 ok = (protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
1943 /* -1 means we didn't see a size in the response */
1944 if (len == -1 && msgsizes)
1946 len = msgsizes[num - 1];
1950 if (outlevel > O_SILENT)
1952 report_build(stdout, _("reading message %d of %d"),
1956 report_build(stdout, _(" (%d %soctets)"),
1957 len, wholesize ? "" : _("header "));
1958 if (outlevel >= O_VERBOSE)
1959 report_complete(stdout, "\n");
1961 report_complete(stdout, " ");
1965 * Read the message headers and ship them to the
1968 ok = readheaders(mailserver_socket, len, msgsizes[num-1],
1970 if (ok == PS_RETAINED)
1971 suppress_forward = retained = TRUE;
1972 else if (ok == PS_TRANSIENT)
1973 suppress_delete = suppress_forward = TRUE;
1974 else if (ok == PS_REFUSED)
1975 suppress_forward = TRUE;
1976 else if (ok == PS_TRUNCATED)
1977 suppress_readbody = TRUE;
1982 * If we're using IMAP4 or something else that
1983 * can fetch headers separately from bodies,
1984 * it's time to request the body now. This
1985 * fetch may be skipped if we got an anti-spam
1986 * or other PS_REFUSED error response during
1989 if (protocol->fetch_body && !suppress_readbody)
1991 if (outlevel >= O_VERBOSE)
1993 fputc('\n', stdout);
1997 if ((ok = (protocol->trail)(mailserver_socket, ctl, num)))
2000 if (!suppress_forward)
2002 if ((ok=(protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
2005 * Work around a bug in Novell's
2006 * broken GroupWise IMAP server;
2007 * its body FETCH response is missing
2008 * the required length for the data
2009 * string. This violates RFC2060.
2012 len = msgsizes[num-1] - msglen;
2013 if (outlevel > O_SILENT && !wholesize)
2014 report_complete(stdout,
2015 _(" (%d body octets) "), len);
2019 /* process the body now */
2022 if (suppress_readbody)
2024 /* When readheaders returns PS_TRUNCATED,
2025 the body (which has no content
2026 has already been read by readheaders,
2027 so we say readbody returned PS_SUCCESS */
2032 ok = readbody(mailserver_socket,
2037 if (ok == PS_TRANSIENT)
2038 suppress_delete = suppress_forward = TRUE;
2042 /* tell server we got it OK and resynchronize */
2043 if (protocol->trail)
2045 if (outlevel >= O_VERBOSE)
2047 fputc('\n', stdout);
2051 ok = (protocol->trail)(mailserver_socket, ctl, num);
2057 /* count # messages forwarded on this pass */
2058 if (!suppress_forward)
2062 * Check to see if the numbers matched?
2064 * Yes, some servers foo this up horribly.
2065 * All IMAP servers seem to get it right, and
2066 * so does Eudora QPOP at least in 2.xx
2069 * Microsoft Exchange gets it completely
2070 * wrong, reporting compressed rather than
2071 * actual sizes (so the actual length of
2072 * message is longer than the reported size).
2073 * Another fine example of Microsoft brain death!
2075 * Some older POP servers, like the old UCB
2076 * POP server and the pre-QPOP QUALCOMM
2077 * versions, report a longer size in the LIST
2078 * response than actually gets shipped up.
2079 * It's unclear what is going on here, as the
2080 * QUALCOMM server (at least) seems to be
2081 * reporting the on-disk size correctly.
2083 if (msgsizes && msglen != msgsizes[num-1])
2085 if (outlevel >= O_DEBUG)
2087 _("message %d was not the expected length (%d actual != %d expected)\n"),
2088 num, msglen, msgsizes[num-1]);
2091 /* end-of-message processing starts here */
2092 if (!close_sink(ctl, &msgblk, !suppress_forward))
2095 suppress_delete = TRUE;
2101 * At this point in flow of control, either
2102 * we've bombed on a protocol error or had
2103 * delivery refused by the SMTP server
2104 * (unlikely -- I've never seen it) or we've
2105 * seen `accepted for delivery' and the
2106 * message is shipped. It's safe to mark the
2107 * message seen and delete it on the server
2111 /* tell the UID code we've seen this */
2116 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2117 if (sdp->val.status.num == num)
2118 sdp->val.status.mark = UID_SEEN;
2121 /* maybe we delete this message now? */
2124 if (outlevel > O_SILENT)
2125 report(stdout, _(" retained\n"));
2127 else if (protocol->delete
2129 && (fetch_it ? !ctl->keep : ctl->flush))
2132 if (outlevel > O_SILENT)
2133 report_complete(stdout, _(" flushed\n"));
2134 ok = (protocol->delete)(mailserver_socket, ctl, num);
2138 delete_str(&ctl->newsaved, num);
2139 #endif /* POP3_ENABLE */
2141 else if (outlevel > O_SILENT)
2142 report_complete(stdout, _(" not flushed\n"));
2144 /* perhaps this as many as we're ready to handle */
2145 if (maxfetch && maxfetch <= fetches && fetches < count)
2147 report(stdout, _("fetchlimit %d reached; %d messages left on server\n"),
2148 maxfetch, count - fetches);
2154 if (!check_only && ctl->skipped
2155 && run.poll_interval > 0 && !nodetach)
2157 clean_skipped_list(&ctl->skipped);
2158 send_size_warnings(ctl);
2163 * Only re-poll if we had some actual forwards, allowed
2164 * deletions and had no errors.
2165 * Otherwise it is far too easy to get into infinite loops.
2167 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2171 /* ordinary termination with no errors -- officially log out */
2172 ok = (protocol->logout_cmd)(mailserver_socket, ctl);
2174 * Hmmmm...arguably this would be incorrect if we had fetches but
2175 * no dispatches (due to oversized messages, etc.)
2178 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2179 SockClose(mailserver_socket);
2183 /* we only get here on error */
2184 if (ok != 0 && ok != PS_SOCKET)
2185 (protocol->logout_cmd)(mailserver_socket, ctl);
2186 SockClose(mailserver_socket);
2189 msg = (const char *)NULL; /* sacrifice to -Wall */
2196 msg = _("authorization");
2199 msg = _("missing or bad RFC822 header");
2205 msg = _("client/server synchronization");
2208 msg = _("client/server protocol");
2211 msg = _("lock busy on server");
2214 msg = _("SMTP transaction");
2217 msg = _("DNS lookup");
2220 report(stderr, _("undefined error\n"));
2223 /* no report on PS_MAXFETCH or PS_UNDEFINED */
2224 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2225 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2226 || ok==PS_LOCKBUSY || ok==PS_SMTP || ok==PS_DNS)
2227 report(stderr, _("%s error while fetching from %s\n"), msg, ctl->server.pollname);
2230 /* execute post-initialization command, if any */
2231 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2233 report(stderr, _("post-connection command failed with status %d\n"), ok);
2234 if (ok == PS_SUCCESS)
2238 signal(SIGALRM, alrmsave);
2239 signal(SIGPIPE, pipesave);
2243 int do_protocol(ctl, proto)
2244 /* retrieve messages from server using given protocol method table */
2245 struct query *ctl; /* parsed options with merged-in defaults */
2246 const struct method *proto; /* protocol method table */
2251 if (ctl->server.preauthenticate == A_KERBEROS_V4)
2253 report(stderr, _("Kerberos V4 support not linked.\n"));
2256 #endif /* KERBEROS_V4 */
2259 if (ctl->server.preauthenticate == A_KERBEROS_V5)
2261 report(stderr, _("Kerberos V5 support not linked.\n"));
2264 #endif /* KERBEROS_V5 */
2266 /* lacking methods, there are some options that may fail */
2269 /* check for unsupported options */
2272 _("Option --flush is not supported with %s\n"),
2276 else if (ctl->fetchall) {
2278 _("Option --all is not supported with %s\n"),
2283 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
2286 _("Option --limit is not supported with %s\n"),
2292 * If no expunge limit or we do expunges within the driver,
2293 * then just do one session, passing in any fetchlimit.
2295 if (proto->retry || !NUM_SPECIFIED(ctl->expunge))
2296 return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
2298 * There's an expunge limit, and it isn't handled in the driver itself.
2299 * OK; do multiple sessions, each fetching a limited # of messages.
2300 * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
2301 * (if it was nonzero).
2307 int expunge = NUM_VALUE_OUT(ctl->expunge);
2308 int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
2311 ok = do_session(ctl, proto, expunge);
2312 totalcount += expunge;
2313 if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
2315 if (ok != PS_LOCKBUSY)
2317 else if (lockouts >= MAX_LOCKOUTS)
2319 else /* ok == PS_LOCKBUSY */
2322 * Allow time for the server lock to release. if we
2323 * don't do this, we'll often hit a locked-mailbox
2324 * condition and fail.
2330 (ok == PS_MAXFETCH || ok == PS_LOCKBUSY);
2336 #if defined(HAVE_STDARG_H)
2337 void gen_send(int sock, const char *fmt, ... )
2339 void gen_send(sock, fmt, va_alist)
2340 int sock; /* socket to which server is connected */
2341 const char *fmt; /* printf-style format */
2344 /* assemble command in printf(3) style and send to the server */
2346 char buf [MSGBUFSIZE+1];
2349 if (protocol->tagged)
2350 (void) sprintf(buf, "%s ", GENSYM);
2354 #if defined(HAVE_STDARG_H)
2359 #ifdef HAVE_VSNPRINTF
2360 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2362 vsprintf(buf + strlen(buf), fmt, ap);
2366 strcat(buf, "\r\n");
2367 SockWrite(sock, buf, strlen(buf));
2369 if (outlevel >= O_MONITOR)
2373 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2377 sp = cp + strlen(shroud);
2383 buf[strlen(buf)-2] = '\0';
2384 report(stdout, "%s> %s\n", protocol->name, buf);
2388 int gen_recv(sock, buf, size)
2389 /* get one line of input from the server */
2390 int sock; /* socket to which server is connected */
2391 char *buf; /* buffer to receive input */
2392 int size; /* length of buffer */
2394 int oldphase = phase; /* we don't have to be re-entrant */
2396 phase = SERVER_WAIT;
2397 set_timeout(mytimeout);
2398 if (SockRead(sock, buf, size) == -1)
2407 if (buf[strlen(buf)-1] == '\n')
2408 buf[strlen(buf)-1] = '\0';
2409 if (buf[strlen(buf)-1] == '\r')
2410 buf[strlen(buf)-1] = '\0';
2411 if (outlevel >= O_MONITOR)
2412 report(stdout, "%s< %s\n", protocol->name, buf);
2418 #if defined(HAVE_STDARG_H)
2419 int gen_transact(int sock, const char *fmt, ... )
2421 int gen_transact(int sock, fmt, va_alist)
2422 int sock; /* socket to which server is connected */
2423 const char *fmt; /* printf-style format */
2426 /* assemble command in printf(3) style, send to server, accept a response */
2429 char buf [MSGBUFSIZE+1];
2431 int oldphase = phase; /* we don't have to be re-entrant */
2433 phase = SERVER_WAIT;
2435 if (protocol->tagged)
2436 (void) sprintf(buf, "%s ", GENSYM);
2440 #if defined(HAVE_STDARG_H)
2445 #ifdef HAVE_VSNPRINTF
2446 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2448 vsprintf(buf + strlen(buf), fmt, ap);
2452 strcat(buf, "\r\n");
2453 SockWrite(sock, buf, strlen(buf));
2455 if (outlevel >= O_MONITOR)
2459 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2463 sp = cp + strlen(shroud);
2469 buf[strlen(buf)-1] = '\0';
2470 report(stdout, "%s> %s\n", protocol->name, buf);
2473 /* we presume this does its own response echoing */
2474 ok = (protocol->parse_response)(sock, buf);
2480 /* driver.c ends here */