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 #ifndef strstr /* glibc-2.1 declares this as a macro */
73 extern char *strstr(); /* needed on sysV68 R3V7.1. */
76 int fetchlimit; /* how often to tear down the server connection */
77 int batchcount; /* count of messages sent in current batch */
78 flag peek_capable; /* can we peek for better error recovery? */
79 int pass; /* how many times have we re-polled? */
80 int phase; /* where are we, for error-logging purposes? */
82 static const struct method *protocol;
83 static jmp_buf restart;
87 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
89 static char shroud[PASSWORDLEN]; /* string to shroud in debug output */
90 static int mytimeout; /* value of nonreponse timeout */
91 static int timeoutcount; /* count consecutive timeouts */
92 static int msglen; /* actual message length */
94 void set_timeout(int timeleft)
95 /* reset the nonresponse-timeout */
98 struct itimerval ntimeout;
103 ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
104 ntimeout.it_value.tv_sec = timeleft;
105 ntimeout.it_value.tv_usec = 0;
106 setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
110 static void timeout_handler (int signal)
111 /* handle server-timeout SIGALRM signal */
117 static int accept_count, reject_count;
119 static void map_name(const char *name, struct query *ctl, struct idlist **xmit_names)
120 /* add given name to xmit_names if it matches declared localnames */
121 /* name: name to map */
122 /* ctl: list of permissible aliases */
123 /* xmit_names: list of recipient names parsed out */
128 lname = idpair_find(&ctl->localnames, name+off);
129 if (!lname && ctl->wildcard)
132 if (lname != (char *)NULL)
134 if (outlevel >= O_DEBUG)
135 progress(0, 0, _("mapped %s to local %s"), name, lname);
136 save_str(xmit_names, lname, XMIT_ACCEPT);
141 static void find_server_names(const char *hdr,
143 struct idlist **xmit_names)
144 /* parse names out of a RFC822 header into an ID list */
145 /* hdr: RFC822 header in question */
146 /* ctl: list of permissible aliases */
147 /* xmit_names: list of recipient names parsed out */
149 if (hdr == (char *)NULL)
155 for (cp = nxtaddr(hdr);
162 * If the name of the user begins with a qmail virtual
163 * domain prefix, ignore the prefix. Doing this here
164 * means qvirtual will work either with ordinary name
165 * mapping or with a localdomains option.
167 if (ctl->server.qvirtual)
169 int sl = strlen(ctl->server.qvirtual);
171 if (!strncasecmp(cp, ctl->server.qvirtual, sl))
175 if ((atsign = strchr(cp, '@'))) {
179 * Does a trailing segment of the hostname match something
180 * on the localdomains list? If so, save the whole name
183 for (idp = ctl->server.localdomains; idp; idp = idp->next) {
186 rhs = atsign + (strlen(atsign) - strlen(idp->id));
188 (rhs[-1] == '.' || rhs[-1] == '@') &&
189 strcasecmp(rhs, idp->id) == 0)
191 if (outlevel >= O_DEBUG)
192 progress(0, 0, _("passed through %s matching %s"),
194 save_str(xmit_names, cp, XMIT_ACCEPT);
200 /* if we matched a local domain, idp != NULL */
204 * Check to see if the right-hand part is an alias
205 * or MX equivalent of the mailserver. If it's
206 * not, skip this name. If it is, we'll keep
207 * going and try to find a mapping to a client name.
209 if (!is_host_alias(atsign+1, ctl))
211 save_str(xmit_names, cp, XMIT_REJECT);
217 map_name(cp, ctl, xmit_names);
224 static char *parse_received(struct query *ctl, char *bufp)
225 /* try to extract real address from the Received line */
226 /* If a valid Received: line is found, we return the full address in
227 * a buffer which can be parsed from nxtaddr(). This is to ansure that
228 * the local domain part of the address can be passed along in
229 * find_server_names() if it contains one.
230 * Note: We should return a dummy header containing the address
231 * which makes nxtaddr() behave correctly.
234 char *base, *ok = (char *)NULL;
235 static char rbuf[HOSTLEN + USERNAMELEN + 4];
238 * Try to extract the real envelope addressee. We look here
239 * specifically for the mailserver's Received line.
240 * Note: this will only work for sendmail, or an MTA that
241 * shares sendmail's convention for embedding the envelope
242 * address in the Received line. Sendmail itself only
243 * does this when the mail has a single recipient.
245 if (outlevel >= O_DEBUG)
246 progress(0, 0, _("analyzing Received line:\n%s"), bufp);
248 /* search for whitepace-surrounded "by" followed by xxxx.yyyy */
249 for (base = bufp; ; base = ok + 2)
251 if (!(ok = strstr(base, "by")))
253 else if (!isspace(ok[-1]) || !isspace(ok[2]))
259 /* extract space-delimited token after "by" */
260 for (sp = ok + 2; isspace(*sp); sp++)
263 for (; !isspace(*sp); sp++)
267 /* look for embedded periods */
268 if (strchr(rbuf, '.'))
271 ok = sp - 1; /* arrange to skip this token */
277 * If it's a DNS name of the mail server, look for the
278 * recipient name after a following "for". Otherwise
281 if (is_host_alias(rbuf, ctl))
283 if (outlevel >= O_DEBUG)
285 _("line accepted, %s is an alias of the mailserver"), rbuf);
289 if (outlevel >= O_DEBUG)
291 _("line rejected, %s is not an alias of the mailserver"),
296 /* search for whitepace-surrounded "for" followed by xxxx@yyyy */
297 for (base = ok + 4 + strlen(rbuf); ; base = ok + 2)
299 if (!(ok = strstr(base, "for")))
301 else if (!isspace(ok[-1]) || !isspace(ok[3]))
307 /* extract space-delimited token after "for" */
308 for (sp = ok + 3; isspace(*sp); sp++)
311 for (; !isspace(*sp); sp++)
315 if (strchr(rbuf, '@'))
318 ok = sp - 1; /* arrange to skip this token */
323 flag want_gt = FALSE;
326 /* char after "for" could be space or a continuation newline */
327 for (sp = ok + 4; isspace(*sp); sp++)
330 *tp++ = ':'; /* Here is the hack. This is to be friends */
331 *tp++ = ' '; /* with nxtaddr()... */
337 while (*sp == '@') /* skip routes */
338 while (*sp && *sp++ != ':')
341 && (want_gt ? (*sp != '>') : !isspace(*sp))
347 /* uh oh -- whitespace here can't be right! */
353 if (strlen(rbuf) <= 3) /* apparently nothing has been found */
361 if (outlevel >= O_DEBUG)
362 progress(0, 0, _("no Received address found"));
367 if (outlevel >= O_DEBUG) {
368 char *lf = rbuf + strlen(rbuf)-1;
370 if (outlevel >= O_DEBUG)
371 progress(0, 0, _("found Received address `%s'"), rbuf+2);
378 /* shared by readheaders and readbody */
379 static int sizeticker;
380 static struct msgblk msgblk;
382 #define EMPTYLINE(s) ((s)[0] == '\r' && (s)[1] == '\n' && (s)[2] == '\0')
384 static int readheaders(int sock,
389 /* read message headers and ship to SMTP or MDA */
390 /* sock: to which the server is connected */
391 /* fetchlen: length of message according to fetch response */
392 /* reallen: length of message according to getsizes */
393 /* ctl: query control record */
394 /* num: index of message */
399 struct addrblk *next;
401 struct addrblk *to_addrchain = NULL;
402 struct addrblk **to_chainptr = &to_addrchain;
403 struct addrblk *resent_to_addrchain = NULL;
404 struct addrblk **resent_to_chainptr = &resent_to_addrchain;
406 char buf[MSGBUFSIZE+1];
407 int from_offs, reply_to_offs, resent_from_offs;
408 int app_from_offs, sender_offs, resent_sender_offs;
410 char *received_for, *rcv, *cp;
411 int n, linelen, oldlen, ch, remaining, skipcount;
413 flag no_local_matches = FALSE;
414 flag headers_ok, has_nuls;
415 int olderrs, good_addresses, bad_addresses;
418 has_nuls = headers_ok = FALSE;
419 msgblk.return_path[0] = '\0';
420 olderrs = ctl->errcount;
422 /* read message headers */
423 msgblk.reallen = reallen;
424 msgblk.headers = received_for = NULL;
425 from_offs = reply_to_offs = resent_from_offs = app_from_offs =
426 sender_offs = resent_sender_offs = env_offs = -1;
432 for (remaining = fetchlen; remaining > 0 || protocol->delimited; remaining -= linelen)
436 line = xmalloc(sizeof(buf));
440 set_timeout(mytimeout);
441 if ((n = SockRead(sock, buf, sizeof(buf)-1)) == -1) {
444 free(msgblk.headers);
451 /* lines may not be properly CRLF terminated; fix this for qmail */
454 cp = buf + strlen(buf) - 1;
455 if (*cp == '\n' && (cp == buf || cp[-1] != '\r'))
464 line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
468 /* check for end of headers */
472 has_nuls = (linelen != strlen(line));
474 goto process_headers;
478 * Check for end of message immediately. If one of your folders
479 * has been mangled, the delimiter may occur directly after the
482 if (protocol->delimited && line[0] == '.' && EMPTYLINE(line+1))
485 has_nuls = (linelen != strlen(line));
486 goto process_headers;
489 /* check for RFC822 continuations */
490 set_timeout(mytimeout);
494 (ch == ' ' || ch == '\t'); /* continuation to next line? */
496 /* write the message size dots */
497 if ((outlevel > O_SILENT && outlevel < O_VERBOSE) && linelen > 0)
499 sizeticker += linelen;
500 while (sizeticker >= SIZETICKER)
503 sizeticker -= SIZETICKER;
507 /* we see an ordinary (non-header, non-message-delimiter line */
508 has_nuls = (linelen != strlen(line));
511 * The University of Washington IMAP server (the reference
512 * implementation of IMAP4 written by Mark Crispin) relies
513 * on being able to keep base-UID information in a special
514 * message at the head of the mailbox. This message should
515 * neither be deleted nor forwarded.
519 * We disable this check under POP2 because there's no way to
520 * prevent deletion of the message. So at least we ought to
521 * forward it to the user so he or she will have some clue
522 * that things have gone awry.
524 if (protocol->port != 109)
525 #endif /* POP2_ENABLE */
526 if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
528 free(msgblk.headers);
533 * This code prevents fetchmail from becoming an accessory after
534 * the fact to upstream sendmails with the `E' option on. It also
535 * copes with certain brain-dead POP servers (like NT's) that pass
536 * through Unix from_ lines.
538 * Either of these bugs can result in a non-RFC822 line at the
539 * beginning of the headers. If fetchmail just passes it
540 * through, the client listener may think the message has *no*
541 * headers (since the first) line it sees doesn't look
542 * RFC822-conformant) and fake up a set.
544 * What the user would see in this case is bogus (synthesized)
545 * headers, followed by a blank line, followed by the >From,
546 * followed by the real headers, followed by a blank line,
549 * We forestall this lossage by tossing anything that looks
550 * like an escaped or passed-through From_ line in headers.
551 * These aren't RFC822 so our conscience is clear...
553 if (!strncasecmp(line, ">From ", 6) || !strncasecmp(line, "From ", 5))
560 * If we see a Status line, it may have been inserted by an MUA
561 * on the mail host, or it may have been inserted by the server
562 * program after the headers in the transaction stream. This
563 * can actually hose some new-mail notifiers such as xbuffy,
564 * which assumes any Status line came from a *local* MDA and
565 * therefore indicates that the message has been seen.
567 * Some buggy POP servers (including at least the 3.3(20)
568 * version of the one distributed with IMAP) insert empty
569 * Status lines in the transaction stream; we'll chuck those
570 * unconditionally. Nonempty ones get chucked if the user
571 * turns on the dropstatus flag.
576 if (!strncasecmp(line, "Status:", 7))
578 else if (!strncasecmp(line, "X-Mozilla-Status:", 17))
583 while (*cp && isspace(*cp)) cp++;
584 if (!*cp || ctl->dropstatus)
593 line = reply_hack(line, ctl->server.truename);
596 * OK, this is messy. If we're forwarding by SMTP, it's the
597 * SMTP-receiver's job (according to RFC821, page 22, section
598 * 4.1.1) to generate a Return-Path line on final delivery.
599 * The trouble is, we've already got one because the
600 * mailserver's SMTP thought *it* was responsible for final
603 * Stash away the contents of Return-Path (as modified by reply_hack)
604 * for use in generating MAIL FROM later on, then prevent the header
605 * from being saved with the others. In effect, we strip it off here.
607 * If the SMTP server conforms to the standards, and fetchmail gets the
608 * envelope sender from the Return-Path, the new Return-Path should be
609 * exactly the same as the original one.
611 * We do *not* want to ignore empty Return-Path headers. These should
612 * be passed through as a way of indicating that a message should
613 * not trigger bounces if delivery fails. What we *do* need to do is
614 * make sure we never try to rewrite such a blank Return-Path. We
615 * handle this with a check for <> in the rewrite logic above.
617 if (!strncasecmp("Return-Path:", line, 12) && (cp = nxtaddr(line)))
619 strcpy(msgblk.return_path, cp);
628 oldlen = strlen(line);
629 msgblk.headers = xmalloc(oldlen + 1);
630 (void) strcpy(msgblk.headers, line);
632 line = msgblk.headers;
638 newlen = oldlen + strlen(line);
639 msgblk.headers = (char *) realloc(msgblk.headers, newlen + 1);
640 if (msgblk.headers == NULL) {
644 strcpy(msgblk.headers + oldlen, line);
646 line = msgblk.headers + oldlen;
650 if (!strncasecmp("From:", line, 5))
651 from_offs = (line - msgblk.headers);
652 else if (!strncasecmp("Reply-To:", line, 9))
653 reply_to_offs = (line - msgblk.headers);
654 else if (!strncasecmp("Resent-From:", line, 12))
655 resent_from_offs = (line - msgblk.headers);
656 else if (!strncasecmp("Apparently-From:", line, 16))
657 app_from_offs = (line - msgblk.headers);
658 else if (!strncasecmp("Sender:", line, 7))
659 sender_offs = (line - msgblk.headers);
660 else if (!strncasecmp("Resent-Sender:", line, 14))
661 resent_sender_offs = (line - msgblk.headers);
663 else if (!strncasecmp("Message-Id:", buf, 11))
665 if (ctl->server.uidl)
669 buf[IDLEN+12] = 0; /* prevent stack overflow */
670 sscanf(buf+12, "%s", id);
671 if (!str_find( &ctl->newsaved, num))
673 struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
674 new->val.status.num = num;
679 else if (!MULTIDROP(ctl))
682 else if (!strncasecmp("To:", line, 3)
683 || !strncasecmp("Cc:", line, 3)
684 || !strncasecmp("Bcc:", line, 4)
685 || !strncasecmp("Apparently-To:", line, 14))
687 *to_chainptr = xmalloc(sizeof(struct addrblk));
688 (*to_chainptr)->offset = (line - msgblk.headers);
689 to_chainptr = &(*to_chainptr)->next;
693 else if (!strncasecmp("Resent-To:", line, 10)
694 || !strncasecmp("Resent-Cc:", line, 10)
695 || !strncasecmp("Resent-Bcc:", line, 11))
697 *resent_to_chainptr = xmalloc(sizeof(struct addrblk));
698 (*resent_to_chainptr)->offset = (line - msgblk.headers);
699 resent_to_chainptr = &(*resent_to_chainptr)->next;
700 *resent_to_chainptr = NULL;
703 else if (ctl->server.envelope != STRING_DISABLED)
705 if (ctl->server.envelope
706 && strcasecmp(ctl->server.envelope, "Received"))
708 if (env_offs == -1 && !strncasecmp(ctl->server.envelope,
710 strlen(ctl->server.envelope)))
712 if (skipcount++ != ctl->server.envskip)
714 env_offs = (line - msgblk.headers);
717 else if (!received_for && !strncasecmp("Received:", line, 9))
719 if (skipcount++ != ctl->server.envskip)
721 received_for = parse_received(ctl, line);
728 * We want to detect this early in case there are so few headers that the
729 * dispatch logic barfs.
733 if (outlevel > O_SILENT)
734 progress(0,0,_("message delimiter found while scanning headers"));
738 * Hack time. If the first line of the message was blank, with no headers
739 * (this happens occasionally due to bad gatewaying software) cons up
740 * a set of fake headers.
742 * If you modify the fake header template below, be sure you don't
743 * make either From or To address @-less, otherwise the reply_hack
744 * logic will do bad things.
746 if (msgblk.headers == (char *)NULL)
749 snprintf(buf, sizeof(buf),
752 #endif /* HAVE_SNPRINTF */
753 "From: FETCHMAIL-DAEMON\r\nTo: %s@%s\r\nSubject: Headerless mail from %s's mailbox on %s\r\n",
754 user, fetchmailhost, ctl->remotename, ctl->server.truename);
755 msgblk.headers = xstrdup(buf);
759 * We can now process message headers before reading the text.
760 * In fact we have to, as this will tell us where to forward to.
763 /* Decode MIME encoded headers. We MUST do this before
764 * looking at the Content-Type / Content-Transfer-Encoding
765 * headers (RFC 2046).
767 if (ctl->mimedecode) {
768 UnMimeHeader(msgblk.headers);
770 /* Check for MIME headers indicating possible 8-bit data */
771 ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
774 * If there is a Return-Path address on the message, this was
775 * almost certainly the MAIL FROM address given the originating
776 * sendmail. This is the best thing to use for logging the
777 * message origin (it sets up the right behavior for bounces and
778 * mailing lists). Otherwise, fall down to the next available
779 * envelope address (which is the most probable real sender).
780 * *** The order is important! ***
781 * This is especially useful when receiving mailing list
782 * messages in multidrop mode. if a local address doesn't
783 * exist, the bounce message won't be returned blindly to the
784 * author or to the list itself but rather to the list manager
785 * (ex: specified by "Sender:") which is much less annoying. This
786 * is true for most mailing list packages.
788 if( !msgblk.return_path[0] ){
790 if (resent_sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_sender_offs)));
791 else if (sender_offs >= 0 && (ap = nxtaddr(msgblk.headers + sender_offs)));
792 else if (resent_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + resent_from_offs)));
793 else if (from_offs >= 0 && (ap = nxtaddr(msgblk.headers + from_offs)));
794 else if (reply_to_offs >= 0 && (ap = nxtaddr(msgblk.headers + reply_to_offs)));
795 else if (app_from_offs >= 0 && (ap = nxtaddr(msgblk.headers + app_from_offs)));
796 if (ap) strcpy( msgblk.return_path, ap );
799 /* cons up a list of local recipients */
800 msgblk.recipients = (struct idlist *)NULL;
801 accept_count = reject_count = 0;
802 /* is this a multidrop box? */
805 if (env_offs > -1) /* We have the actual envelope addressee */
806 find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
807 else if (received_for)
809 * We have the Received for addressee.
810 * It has to be a mailserver address, or we
811 * wouldn't have got here.
812 * We use find_server_names() to let local
813 * hostnames go through.
815 find_server_names(received_for, ctl, &msgblk.recipients);
819 find_server_names(sdps_envto, ctl, &msgblk.recipients);
822 #endif /* SDPS_ENABLE */
826 * We haven't extracted the envelope address.
827 * So check all the "Resent-To" header addresses if
828 * they exist. If and only if they don't, consider
831 register struct addrblk *nextptr;
832 if (resent_to_addrchain) {
833 /* delete the "To" chain and substitute it
834 * with the "Resent-To" list
836 while (to_addrchain) {
837 nextptr = to_addrchain->next;
839 to_addrchain = nextptr;
841 to_addrchain = resent_to_addrchain;
842 resent_to_addrchain = NULL;
844 /* now look for remaining adresses */
845 while (to_addrchain) {
846 find_server_names(msgblk.headers+to_addrchain->offset, ctl, &msgblk.recipients);
847 nextptr = to_addrchain->next;
849 to_addrchain = nextptr;
854 no_local_matches = TRUE;
855 save_str(&msgblk.recipients, run.postmaster, XMIT_ACCEPT);
856 if (outlevel >= O_DEBUG)
858 _("no local matches, forwarding to %s"),
862 else /* it's a single-drop box, use first localname */
863 save_str(&msgblk.recipients, ctl->localnames->id, XMIT_ACCEPT);
867 * Time to either address the message or decide we can't deliver it yet.
869 if (ctl->errcount > olderrs) /* there were DNS errors above */
871 if (outlevel >= O_DEBUG)
872 progress(0,0, _("forwarding and deletion suppressed due to DNS errors"));
873 free(msgblk.headers);
874 free_str_list(&msgblk.recipients);
875 return(PS_TRANSIENT);
879 /* set up stuffline() so we can deliver the message body through it */
880 if ((n = open_sink(ctl, &msgblk,
881 &good_addresses, &bad_addresses)) != PS_SUCCESS)
883 free(msgblk.headers);
884 free_str_list(&msgblk.recipients);
891 * Some server/sendmail combinations cause problems when our
892 * synthetic Received line is before the From header. Cope
895 if ((rcv = strstr(msgblk.headers, "Received:")) == (char *)NULL)
896 rcv = msgblk.headers;
897 /* handle ">Received:" lines too */
898 while (rcv > msgblk.headers && rcv[-1] != '\n')
900 if (rcv > msgblk.headers)
905 n = stuffline(ctl, msgblk.headers);
908 if (!run.invisible && n != -1)
910 /* utter any per-message Received information we need here */
911 sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
912 n = stuffline(ctl, buf);
916 * This header is technically invalid under RFC822.
917 * POP3, IMAP, etc. are not legal mail-parameter values.
919 * We used to include ctl->remotename in this log line,
920 * but this can be secure information that would be bad
923 sprintf(buf, "\tby %s with %s (fetchmail-%s)\r\n",
927 n = stuffline(ctl, buf);
931 if (good_addresses == 0)
934 "for %s@%s (by default); ",
935 user, ctl->destaddr);
937 else if (good_addresses == 1)
939 for (idp = msgblk.recipients; idp; idp = idp->next)
940 if (idp->val.status.mark == XMIT_ACCEPT)
941 break; /* only report first address */
942 if (strchr(idp->id, '@'))
943 sprintf(buf+1, "for %s", idp->id);
946 * This could be a bit misleading, as destaddr is
947 * the forwarding host rather than the actual
948 * destination. Most of the time they coincide.
950 sprintf(buf+1, "for %s@%s", idp->id, ctl->destaddr);
951 sprintf(buf+strlen(buf), " (%s); ",
952 MULTIDROP(ctl) ? "multi-drop" : "single-drop");
957 strcat(buf, rfc822timestamp());
959 n = stuffline(ctl, buf);
965 n = stuffline(ctl, rcv); /* ship out rest of msgblk.headers */
969 progress(0, errno, _("writing RFC822 msgblk.headers"));
971 free(msgblk.headers);
972 free_str_list(&msgblk.recipients);
975 else if (!run.use_syslog && outlevel >= O_VERBOSE)
978 /* write error notifications */
979 if (no_local_matches || has_nuls || bad_addresses)
982 char errhd[USERNAMELEN + POPBUFSIZE], *errmsg;
985 (void) strcpy(errhd, "X-Fetchmail-Warning: ");
986 if (no_local_matches)
988 if (reject_count != 1)
989 strcat(errhd, _("no recipient addresses matched declared local names"));
992 for (idp = msgblk.recipients; idp; idp = idp->next)
993 if (idp->val.status.mark == XMIT_REJECT)
995 sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
1001 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1002 strcat(errhd, "; ");
1003 strcat(errhd, _("message has embedded NULs"));
1008 if (errhd[sizeof("X-Fetchmail-Warning: ")])
1009 strcat(errhd, "; ");
1010 strcat(errhd, _("SMTP listener rejected local recipient addresses: "));
1011 errlen = strlen(errhd);
1012 for (idp = msgblk.recipients; idp; idp = idp->next)
1013 if (idp->val.status.mark == XMIT_RCPTBAD)
1014 errlen += strlen(idp->id) + 2;
1016 xalloca(errmsg, char *, errlen+3);
1017 (void) strcpy(errmsg, errhd);
1018 for (idp = msgblk.recipients; idp; idp = idp->next)
1019 if (idp->val.status.mark == XMIT_RCPTBAD)
1021 strcat(errmsg, idp->id);
1023 strcat(errmsg, ", ");
1028 strcat(errmsg, "\r\n");
1030 /* ship out the error line */
1031 stuffline(ctl, errmsg);
1034 /* issue the delimiter line */
1039 stuffline(ctl, buf);
1041 free(msgblk.headers);
1042 free_str_list(&msgblk.recipients);
1043 return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
1046 static int readbody(int sock, struct query *ctl, flag forward, int len)
1047 /* read and dispose of a message body presented on sock */
1048 /* ctl: query control record */
1049 /* sock: to which the server is connected */
1050 /* len: length of message */
1051 /* forward: TRUE to forward */
1054 unsigned char buf[MSGBUFSIZE+4];
1055 unsigned char *inbufp = buf;
1056 flag issoftline = FALSE;
1058 /* pass through the text lines */
1059 while (protocol->delimited || len > 0)
1061 set_timeout(mytimeout);
1062 if ((linelen = SockRead(sock, inbufp, sizeof(buf)-4-(inbufp-buf)))==-1)
1070 /* write the message size dots */
1073 sizeticker += linelen;
1074 while (sizeticker >= SIZETICKER)
1076 if (!run.use_syslog && outlevel > O_SILENT)
1077 progress_build(".");
1078 sizeticker -= SIZETICKER;
1083 /* check for end of message */
1084 if (protocol->delimited && *inbufp == '.')
1085 if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
1087 else if (inbufp[1] == '\n' && inbufp[2] == '\0')
1090 msglen--; /* subtract the size of the dot escape */
1094 if (ctl->mimedecode && (ctl->mimemsg & MSG_NEEDS_DECODE)) {
1095 issoftline = UnMimeBodyline(&inbufp, (protocol->delimited && issoftline));
1096 if (issoftline && (sizeof(buf)-1-(inbufp-buf) < 200))
1099 * Soft linebreak, but less than 200 bytes left in
1100 * input buffer. Rather than doing a buffer overrun,
1101 * ignore the soft linebreak, NL-terminate data and
1102 * deliver what we have now.
1103 * (Who writes lines longer than 2K anyway?)
1105 *inbufp = '\n'; *(inbufp+1) = '\0';
1110 /* ship out the text line */
1111 if (forward && (!issoftline))
1116 /* guard against very long lines */
1117 buf[MSGBUFSIZE+1] = '\r';
1118 buf[MSGBUFSIZE+2] = '\n';
1119 buf[MSGBUFSIZE+3] = '\0';
1121 n = stuffline(ctl, buf);
1125 progress(0, errno, _("writing message text"));
1129 else if (outlevel >= O_VERBOSE)
1139 kerberos_auth (socket, canonical)
1140 /* authenticate to the server host using Kerberos V4 */
1141 int socket; /* socket to server host */
1143 char *canonical; /* server name */
1145 const char *canonical; /* server name */
1148 char * host_primary;
1152 Key_schedule schedule;
1155 xalloca(ticket, KTEXT, sizeof (KTEXT_ST));
1156 rem = (krb_sendauth (0L, socket, ticket, "pop",
1158 ((char *) (krb_realmofhost (canonical))),
1159 ((unsigned long) 0),
1163 ((struct sockaddr_in *) 0),
1164 ((struct sockaddr_in *) 0),
1166 if (rem != KSUCCESS)
1168 error(0, -1, _("kerberos error %s"), (krb_get_err_text (rem)));
1169 return (PS_AUTHFAIL);
1173 #endif /* KERBEROS_V4 */
1176 static int kerberos5_auth(socket, canonical)
1177 /* authenticate to the server host using Kerberos V5 */
1178 int socket; /* socket to server host */
1179 const char *canonical; /* server name */
1181 krb5_error_code retval;
1182 krb5_context context;
1184 krb5_principal client = NULL, server = NULL;
1185 krb5_error *err_ret = NULL;
1187 krb5_auth_context auth_context = NULL;
1189 krb5_init_context(&context);
1190 krb5_init_ets(context);
1191 krb5_auth_con_init(context, &auth_context);
1193 if (retval = krb5_cc_default(context, &ccdef)) {
1194 error(0, 0, "krb5_cc_default: %s", error_message(retval));
1198 if (retval = krb5_cc_get_principal(context, ccdef, &client)) {
1199 error(0, 0, "krb5_cc_get_principal: %s", error_message(retval));
1203 if (retval = krb5_sname_to_principal(context, canonical, "pop",
1206 error(0, 0, "krb5_sname_to_principal: %s", error_message(retval));
1210 retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
1211 "KPOPV1.0", client, server,
1212 AP_OPTS_MUTUAL_REQUIRED,
1213 NULL, /* no data to checksum */
1214 0, /* no creds, use ccache instead */
1218 NULL); /* don't need reply */
1220 krb5_free_principal(context, server);
1221 krb5_free_principal(context, client);
1222 krb5_auth_con_free(context, auth_context);
1225 if (err_ret && err_ret->text.length) {
1226 error(0, 0, _("krb5_sendauth: %s [server says '%*s'] "),
1227 error_message(retval),
1228 err_ret->text.length,
1229 err_ret->text.data);
1230 krb5_free_error(context, err_ret);
1232 error(0, 0, "krb5_sendauth: %s", error_message(retval));
1238 #endif /* KERBEROS_V5 */
1240 static void clean_skipped_list(struct idlist **skipped_list)
1241 /* struct "idlist" contains no "prev" ptr; we must remove unused items first */
1243 struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
1244 prev = current = head = *skipped_list;
1250 /* if item has no reference, remove it */
1251 if (current && current->val.status.mark == 0)
1253 if (current == head) /* remove first item (head) */
1255 head = current->next;
1256 if (current->id) free(current->id);
1258 prev = current = head;
1260 else /* remove middle/last item */
1262 tmp = current->next;
1264 if (current->id) free(current->id);
1269 else /* skip this item */
1272 current = current->next;
1276 *skipped_list = head;
1279 static void send_size_warnings(struct query *ctl)
1280 /* send warning mail with skipped msg; reset msg count when user notified */
1283 int msg_to_send = FALSE;
1284 struct idlist *head=NULL, *current=NULL;
1285 int max_warning_poll_count;
1286 #define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server:"
1288 head = ctl->skipped;
1292 /* don't start a notification message unless we need to */
1293 for (current = head; current; current = current->next)
1294 if (current->val.status.num == 0 && current->val.status.mark)
1300 * There's no good way to recover if we can't send notification mail,
1301 * but it's not a disaster, either, since the skipped mail will not
1304 if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
1306 stuff_warning(ctl, OVERHD);
1308 if (run.poll_interval == 0)
1309 max_warning_poll_count = 0;
1311 max_warning_poll_count = ctl->warnings/run.poll_interval;
1313 /* parse list of skipped msg, adding items to the mail */
1314 for (current = head; current; current = current->next)
1316 if (current->val.status.num == 0 && current->val.status.mark)
1318 nbr = current->val.status.mark;
1319 size = atoi(current->id);
1321 _("\t%d msg %d octets long skipped by fetchmail."),
1324 current->val.status.num++;
1325 current->val.status.mark = 0;
1327 if (current->val.status.num >= max_warning_poll_count)
1328 current->val.status.num = 0;
1331 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1335 int do_protocol(ctl, proto)
1336 /* retrieve messages from server using given protocol method table */
1337 struct query *ctl; /* parsed options with merged-in defaults */
1338 const struct method *proto; /* protocol method table */
1341 #ifdef HAVE_VOLATILE
1342 volatile int sock = -1; /* pacifies -Wall */
1345 #endif /* HAVE_VOLATILE */
1347 void (*sigsave)(int);
1348 struct idlist *current=NULL, *tmp=NULL;
1351 ctl->server.base_protocol = protocol;
1354 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1356 error(0, -1, _("Kerberos V4 support not linked."));
1359 #endif /* KERBEROS_V4 */
1362 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1364 error(0, -1, _("Kerberos V5 support not linked."));
1367 #endif /* KERBEROS_V5 */
1369 /* lacking methods, there are some options that may fail */
1372 /* check for unsupported options */
1375 _("Option --flush is not supported with %s"),
1379 else if (ctl->fetchall) {
1381 _("Option --all is not supported with %s"),
1386 if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
1389 _("Option --limit is not supported with %s"),
1396 tag[0] = '\0'; /* nuke any tag hanging out from previous query */
1399 /* set up the server-nonresponse timeout */
1400 sigsave = signal(SIGALRM, timeout_handler);
1401 mytimeout = ctl->server.timeout;
1403 if ((js = setjmp(restart)) == 1)
1405 #ifdef HAVE_SIGPROCMASK
1407 * Don't rely on setjmp() to restore the blocked-signal mask.
1408 * It does this under BSD but is required not to under POSIX.
1410 * If your Unix doesn't have sigprocmask, better hope it has
1411 * BSD-like behavior. Otherwise you may see fetchmail get
1412 * permanently wedged after a second timeout on a bad read,
1413 * because alarm signals were blocked after the first.
1417 sigfillset(&allsigs);
1418 sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
1419 #endif /* HAVE_SIGPROCMASK */
1421 if (phase == OPEN_WAIT)
1423 _("timeout after %d seconds waiting to connect to server %s."),
1424 ctl->server.timeout, ctl->server.pollname);
1425 else if (phase == SERVER_WAIT)
1427 _("timeout after %d seconds waiting for server %s."),
1428 ctl->server.timeout, ctl->server.pollname);
1429 else if (phase == FORWARDING_WAIT)
1431 _("timeout after %d seconds waiting for %s."),
1432 ctl->server.timeout,
1433 ctl->mda ? "MDA" : "SMTP");
1434 else if (phase == LISTENER_WAIT)
1436 _("timeout after %d seconds waiting for listener to respond."));
1438 progress(0, 0, _("timeout after %d seconds."), ctl->server.timeout);
1441 if (ctl->smtp_socket != -1)
1442 close(ctl->smtp_socket);
1447 * If we've exceeded our threshold for consecutive timeouts,
1448 * try to notify the user, then mark the connection wedged.
1450 if (timeoutcount > MAX_TIMEOUTS
1451 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1454 _("Subject: fetchmail sees repeated timeouts\r\n"));
1456 _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s."),
1459 ctl->server.truename);
1461 _("This could mean that your mailserver is stuck, or that your SMTP listener"));
1463 _("is wedged, or that your mailbox file on the server has been corrupted by"));
1465 _("a server error. You can run `fetchmail -v -v' to diagnose the problem."));
1467 _("Fetchmail won't poll this mailbox again until you restart it."));
1468 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1476 char buf[POPBUFSIZE+1], *realhost;
1477 int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
1479 int fetches, dispatches, oldphase;
1481 int port, fetches, dispatches, oldphase;
1485 /* execute pre-initialization command, if any */
1486 if (ctl->preconnect && (ok = system(ctl->preconnect)))
1488 error(0, 0, _("pre-connection command failed with status %d"), ok);
1493 /* open a socket to the mail server */
1496 set_timeout(mytimeout);
1498 port = ctl->server.port ? ctl->server.port : protocol->port;
1500 realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
1502 if ((sock = SockOpen(realhost,
1503 ctl->server.service ? ctl->server.service : protocol->service,
1504 ctl->server.netsec, ctl->server.plugin)) == -1)
1506 if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
1511 #ifdef HAVE_RES_SEARCH
1512 if (err_no != 0 && h_errno != 0)
1513 error(0, 0, _("fetchmail: internal inconsistency"));
1516 * Avoid generating a bogus error every poll cycle when we're
1517 * in daemon mode but the connection to the outside world
1520 if (err_no == EHOSTUNREACH && run.poll_interval)
1523 error_build(_("fetchmail: %s connection to %s failed"),
1524 protocol->name, ctl->server.pollname);
1525 #ifdef HAVE_RES_SEARCH
1528 if (h_errno == HOST_NOT_FOUND)
1529 error_complete(0, 0, _(": host is unknown"));
1530 else if (h_errno == NO_ADDRESS)
1531 error_complete(0, 0, _(": name is valid but has no IP address"));
1532 else if (h_errno == NO_RECOVERY)
1533 error_complete(0, 0, _(": unrecoverable name server error"));
1534 else if (h_errno == TRY_AGAIN)
1535 error_complete(0, 0, _(": temporary name server error"));
1537 error_complete(0, 0, _(": unknown DNS error %d"), h_errno);
1540 #endif /* HAVE_RES_SEARCH */
1542 error_complete(0, err_no, "");
1555 if (ctl->server.preauthenticate == A_KERBEROS_V4)
1557 set_timeout(mytimeout);
1558 ok = kerberos_auth(sock, ctl->server.truename);
1563 #endif /* KERBEROS_V4 */
1566 if (ctl->server.preauthenticate == A_KERBEROS_V5)
1568 set_timeout(mytimeout);
1569 ok = kerberos5_auth(sock, ctl->server.truename);
1574 #endif /* KERBEROS_V5 */
1576 /* accept greeting message from mail server */
1577 ok = (protocol->parse_response)(sock, buf);
1581 /* try to get authorized to fetch mail */
1582 if (protocol->getauth)
1584 if (protocol->password_canonify)
1585 (protocol->password_canonify)(shroud, ctl->password);
1587 strcpy(shroud, ctl->password);
1589 ok = (protocol->getauth)(sock, ctl, buf);
1592 if (ok == PS_LOCKBUSY)
1593 error(0, -1, _("Lock-busy error on %s@%s"),
1595 ctl->server.truename);
1600 error(0, -1, _("Authorization failure on %s@%s"),
1602 ctl->server.truename);
1605 * If we're running in background, try to mail the
1606 * calling user a heads-up about the authentication
1607 * failure the first time it happens.
1609 if (run.poll_interval
1611 && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
1614 _("Subject: fetchmail authentication failed\r\n"));
1616 _("Fetchmail could not get mail from %s@%s."),
1618 ctl->server.truename);
1620 _("The attempt to get authorization failed."));
1622 _("This probably means your password is invalid."));
1623 close_warning_by_mail(ctl, (struct msgblk *)NULL);
1631 ctl->errcount = fetches = 0;
1633 /* now iterate over each folder selected */
1634 for (idp = ctl->mailboxes; idp; idp = idp->next)
1641 if (outlevel >= O_DEBUG)
1643 progress(0, 0, _("selecting or re-polling folder %s"), idp->id);
1645 progress(0, 0, _("selecting or re-polling default folder"));
1647 /* compute # of messages and number of new messages waiting */
1648 ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
1652 /* show user how many messages we downloaded */
1654 (void) sprintf(buf, _("%s at %s (folder %s)"),
1655 ctl->remotename, ctl->server.truename, idp->id);
1657 (void) sprintf(buf, _("%s at %s"),
1658 ctl->remotename, ctl->server.truename);
1659 if (outlevel > O_SILENT)
1660 if (count == -1) /* only used for ETRN */
1661 progress(0, 0, _("Polling %s"), ctl->server.truename);
1662 else if (count != 0)
1664 if (new != -1 && (count - new) > 0)
1665 progress_build(_("%d %s (%d seen) for %s"),
1666 count, count > 1 ? _("messages") :
1670 progress_build(_("%d %s for %s"),
1671 count, count > 1 ? _("messages") :
1674 progress_complete(0, 0, ".");
1676 progress_complete(0, 0, _(" (%d octets)."), bytes);
1680 /* these are pointless in normal daemon mode */
1681 if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
1682 progress(0, 0, _("No mail for %s"), buf);
1685 /* very important, this is where we leave the do loop */
1691 if (new == -1 || ctl->fetchall)
1693 ok = ((new > 0) ? PS_SUCCESS : PS_NOMAIL);
1698 flag force_retrieval;
1701 * What forces this code is that in POP2 and
1702 * IMAP2bis you can't fetch a message without
1703 * having it marked `seen'. In POP3 and IMAP4, on the
1704 * other hand, you can (peek_capable is set by
1705 * each driver module to convey this; it's not a
1706 * method constant because of the difference between
1707 * IMAP2bis and IMAP4, and because POP3 doesn't peek
1708 * if fetchall is on).
1710 * The result of being unable to peek is that if there's
1711 * any kind of transient error (DNS lookup failure, or
1712 * sendmail refusing delivery due to process-table limits)
1713 * the message will be marked "seen" on the server without
1714 * having been delivered. This is not a big problem if
1715 * fetchmail is running in foreground, because the user
1716 * will see a "skipped" message when it next runs and get
1719 * But in daemon mode this leads to the message
1720 * being silently ignored forever. This is not
1723 * We compensate for this by checking the error
1724 * count from the previous pass and forcing all
1725 * messages to be considered new if it's nonzero.
1727 force_retrieval = !peek_capable && (ctl->errcount > 0);
1730 * We need the size of each message before it's
1731 * loaded in order to pass via the ESMTP SIZE
1732 * option. If the protocol has a getsizes method,
1733 * we presume this means it doesn't get reliable
1734 * sizes from message fetch responses.
1736 if (proto->getsizes)
1740 xalloca(msgsizes, int *, sizeof(int) * count);
1741 for (i = 0; i < count; i++)
1744 ok = (proto->getsizes)(sock, count, msgsizes);
1751 for (i = 0; i < count; i++)
1752 bytes += msgsizes[i];
1756 /* read, forward, and delete messages */
1757 for (num = 1; num <= count; num++)
1759 flag toolarge = NUM_NONZERO(ctl->limit)
1760 && msgsizes && (msgsizes[num-1] > ctl->limit);
1761 flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(sock,ctl,num));
1762 flag fetch_it = !toolarge
1763 && (ctl->fetchall || force_retrieval || !oldmsg);
1764 flag suppress_delete = FALSE;
1765 flag suppress_forward = FALSE;
1766 flag suppress_readbody = FALSE;
1767 flag retained = FALSE;
1770 * This check copes with Post Office/NT's
1771 * annoying habit of randomly prepending bogus
1772 * LIST items of length -1. Patrick Audley
1773 * <paudley@pobox.com> tells us: LIST shows a
1774 * size of -1, RETR and TOP return "-ERR
1775 * System error - couldn't open message", and
1776 * DELE succeeds but doesn't actually delete
1779 if (msgsizes && msgsizes[num-1] == -1)
1781 if (outlevel >= O_VERBOSE)
1783 _("Skipping message %d, length -1"),
1788 /* we may want to reject this message if it's old */
1791 if (outlevel > O_SILENT)
1793 progress_build(_("skipping message %d"), num);
1794 if (toolarge && !check_only)
1799 /* convert sz to string */
1800 sprintf(size, "%d", msgsizes[num-1]);
1802 /* build a list of skipped messages
1803 * val.id = size of msg (string cnvt)
1804 * val.status.num = warning_poll_count
1805 * val.status.mask = nbr of msg this size
1808 current = ctl->skipped;
1810 /* initialise warning_poll_count to the
1811 * current value so that all new msg will
1812 * be included in the next mail
1814 cnt = current? current->val.status.num : 0;
1816 /* if entry exists, increment the count */
1818 str_in_list(¤t, size, FALSE))
1821 current = current->next)
1823 if (strcmp(current->id, size) == 0)
1825 current->val.status.mark++;
1830 /* otherwise, create a new entry */
1831 /* initialise with current poll count */
1834 tmp = save_str(&ctl->skipped, size, 1);
1835 tmp->val.status.num = cnt;
1838 progress_build(_(" (oversized, %d octets)"),
1845 flag wholesize = !protocol->fetch_body;
1847 /* request a message */
1848 ok = (protocol->fetch_headers)(sock,ctl,num, &len);
1852 /* -1 means we didn't see a size in the response */
1853 if (len == -1 && msgsizes)
1855 len = msgsizes[num - 1];
1859 if (outlevel > O_SILENT)
1861 progress_build(_("reading message %d of %d"),
1865 progress_build(_(" (%d %soctets)"),
1866 len, wholesize ? "" : _("header "));
1867 if (outlevel >= O_VERBOSE)
1868 progress_complete(0, 0, "");
1870 progress_build(" ");
1874 * Read the message headers and ship them to the
1877 ok = readheaders(sock, len, msgsizes[num-1],
1879 if (ok == PS_RETAINED)
1880 suppress_forward = retained = TRUE;
1881 else if (ok == PS_TRANSIENT)
1882 suppress_delete = suppress_forward = TRUE;
1883 else if (ok == PS_REFUSED)
1884 suppress_forward = TRUE;
1885 else if (ok == PS_TRUNCATED)
1886 suppress_readbody = TRUE;
1891 * If we're using IMAP4 or something else that
1892 * can fetch headers separately from bodies,
1893 * it's time to request the body now. This
1894 * fetch may be skipped if we got an anti-spam
1895 * or other PS_REFUSED error response during
1898 if (protocol->fetch_body && !suppress_readbody)
1900 if (outlevel >= O_VERBOSE)
1901 fputc('\n', stderr);
1903 if ((ok = (protocol->trail)(sock, ctl, num)))
1906 if (!suppress_forward)
1908 if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
1910 if (outlevel > O_SILENT && !wholesize)
1911 progress_build(_(" (%d body octets) "), len);
1915 /* process the body now */
1918 if (suppress_readbody)
1920 /* When readheaders returns PS_TRUNCATED,
1921 the body (which has no content
1922 has already been read by readheaders,
1923 so we say readbody returned PS_SUCCESS */
1933 if (ok == PS_TRANSIENT)
1934 suppress_delete = suppress_forward = TRUE;
1938 /* tell server we got it OK and resynchronize */
1939 if (protocol->trail)
1941 if (outlevel >= O_VERBOSE)
1942 fputc('\n', stderr);
1944 ok = (protocol->trail)(sock, ctl, num);
1950 /* count # messages forwarded on this pass */
1951 if (!suppress_forward)
1955 * Check to see if the numbers matched?
1957 * Yes, some servers foo this up horribly.
1958 * All IMAP servers seem to get it right, and
1959 * so does Eudora QPOP at least in 2.xx
1962 * Microsoft Exchange gets it completely
1963 * wrong, reporting compressed rather than
1964 * actual sizes (so the actual length of
1965 * message is longer than the reported size).
1966 * Another fine example of Microsoft brain death!
1968 * Some older POP servers, like the old UCB
1969 * POP server and the pre-QPOP QUALCOMM
1970 * versions, report a longer size in the LIST
1971 * response than actually gets shipped up.
1972 * It's unclear what is going on here, as the
1973 * QUALCOMM server (at least) seems to be
1974 * reporting the on-disk size correctly.
1976 if (msgsizes && msglen != msgsizes[num-1])
1978 if (outlevel >= O_DEBUG)
1980 _("message %d was not the expected length (%d actual != %d expected)"),
1981 num, msglen, msgsizes[num-1]);
1984 /* end-of-message processing starts here */
1985 if (!close_sink(ctl, &msgblk, !suppress_forward))
1988 suppress_delete = TRUE;
1994 * At this point in flow of control, either
1995 * we've bombed on a protocol error or had
1996 * delivery refused by the SMTP server
1997 * (unlikely -- I've never seen it) or we've
1998 * seen `accepted for delivery' and the
1999 * message is shipped. It's safe to mark the
2000 * message seen and delete it on the server
2004 /* tell the UID code we've seen this */
2009 for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
2010 if (sdp->val.status.num == num)
2011 sdp->val.status.mark = UID_SEEN;
2014 /* maybe we delete this message now? */
2017 if (outlevel > O_SILENT)
2018 progress_complete(0, 0, _(" retained"));
2020 else if (protocol->delete
2022 && (fetch_it ? !ctl->keep : ctl->flush))
2025 if (outlevel > O_SILENT)
2026 progress_complete(0, 0, _(" flushed"));
2027 ok = (protocol->delete)(sock, ctl, num);
2031 delete_str(&ctl->newsaved, num);
2032 #endif /* POP3_ENABLE */
2034 else if (outlevel > O_SILENT)
2035 progress_complete(0, 0, _(" not flushed"));
2037 /* perhaps this as many as we're ready to handle */
2038 if (NUM_NONZERO(ctl->fetchlimit)
2039 && ctl->fetchlimit <= fetches)
2041 progress(0, 0, _("fetchlimit reached; %d messages left on server"),
2047 if (!check_only && ctl->skipped)
2049 clean_skipped_list(&ctl->skipped);
2050 send_size_warnings(ctl);
2055 * Only re-poll if we had some actual forwards, allowed
2056 * deletions and had no errors.
2057 * Otherwise it is far too easy to get into infinite loops.
2059 (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
2063 /* ordinary termination with no errors -- officially log out */
2064 ok = (protocol->logout_cmd)(sock, ctl);
2066 * Hmmmm...arguably this would be incorrect if we had fetches but
2067 * no dispatches (due to oversized messages, etc.)
2070 ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
2075 /* we only get here on error */
2076 if (ok != 0 && ok != PS_SOCKET)
2077 (protocol->logout_cmd)(sock, ctl);
2081 msg = (const char *)NULL; /* sacrifice to -Wall */
2088 msg = _("authorization");
2091 msg = _("missing or bad RFC822 header");
2097 msg = _("client/server synchronization");
2100 msg = _("client/server protocol");
2103 msg = _("lock busy on server");
2106 msg = _("SMTP transaction");
2109 msg = _("DNS lookup");
2112 error(0, 0, _("undefined"));
2115 if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX
2116 || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL
2117 || ok==PS_LOCKBUSY || ok==PS_SMTP)
2118 error(0,-1, _("%s error while fetching from %s"), msg, ctl->server.pollname);
2121 /* execute post-initialization command, if any */
2122 if (ctl->postconnect && (ok = system(ctl->postconnect)))
2124 error(0, 0, _("post-connection command failed with status %d"), ok);
2125 if (ok == PS_SUCCESS)
2129 signal(SIGALRM, sigsave);
2133 #if defined(HAVE_STDARG_H)
2134 void gen_send(int sock, const char *fmt, ... )
2136 void gen_send(sock, fmt, va_alist)
2137 int sock; /* socket to which server is connected */
2138 const char *fmt; /* printf-style format */
2141 /* assemble command in printf(3) style and send to the server */
2143 char buf [MSGBUFSIZE+1];
2146 if (protocol->tagged)
2147 (void) sprintf(buf, "%s ", GENSYM);
2151 #if defined(HAVE_STDARG_H)
2156 #ifdef HAVE_VSNPRINTF
2157 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2159 vsprintf(buf + strlen(buf), fmt, ap);
2163 strcat(buf, "\r\n");
2164 SockWrite(sock, buf, strlen(buf));
2166 if (outlevel >= O_MONITOR)
2170 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2174 sp = cp + strlen(shroud);
2180 buf[strlen(buf)-2] = '\0';
2181 progress(0, 0, "%s> %s", protocol->name, buf);
2185 int gen_recv(sock, buf, size)
2186 /* get one line of input from the server */
2187 int sock; /* socket to which server is connected */
2188 char *buf; /* buffer to receive input */
2189 int size; /* length of buffer */
2191 int oldphase = phase; /* we don't have to be re-entrant */
2193 phase = SERVER_WAIT;
2194 set_timeout(mytimeout);
2195 if (SockRead(sock, buf, size) == -1)
2204 if (buf[strlen(buf)-1] == '\n')
2205 buf[strlen(buf)-1] = '\0';
2206 if (buf[strlen(buf)-1] == '\r')
2207 buf[strlen(buf)-1] = '\0';
2208 if (outlevel >= O_MONITOR)
2209 progress(0, 0, "%s< %s", protocol->name, buf);
2215 #if defined(HAVE_STDARG_H)
2216 int gen_transact(int sock, const char *fmt, ... )
2218 int gen_transact(int sock, fmt, va_alist)
2219 int sock; /* socket to which server is connected */
2220 const char *fmt; /* printf-style format */
2223 /* assemble command in printf(3) style, send to server, accept a response */
2226 char buf [MSGBUFSIZE+1];
2228 int oldphase = phase; /* we don't have to be re-entrant */
2230 phase = SERVER_WAIT;
2232 if (protocol->tagged)
2233 (void) sprintf(buf, "%s ", GENSYM);
2237 #if defined(HAVE_STDARG_H)
2242 #ifdef HAVE_VSNPRINTF
2243 vsnprintf(buf + strlen(buf), sizeof(buf), fmt, ap);
2245 vsprintf(buf + strlen(buf), fmt, ap);
2249 strcat(buf, "\r\n");
2250 SockWrite(sock, buf, strlen(buf));
2252 if (outlevel >= O_MONITOR)
2256 if (shroud && shroud[0] && (cp = strstr(buf, shroud)))
2260 sp = cp + strlen(shroud);
2266 buf[strlen(buf)-1] = '\0';
2267 progress(0, 0, "%s> %s", protocol->name, buf);
2270 /* we presume this does its own response echoing */
2271 ok = (protocol->parse_response)(sock, buf);
2277 /* driver.c ends here */