]> Pileus Git - ~andy/fetchmail/blobdiff - driver.c
Cosmetic cleanup.
[~andy/fetchmail] / driver.c
index 41b0b91d8bd68d9ccb8f2cf489e4724022d2e566..26ff2879f0edd277545dd391ba3c3913a6fc5a6c 100644 (file)
--- a/driver.c
+++ b/driver.c
 #include "fetchmail.h"
 #include "tunable.h"
 
+/* throw types for runtime errors */
+#define THROW_TIMEOUT  1               /* server timed out */
+#define THROW_SIGPIPE  2               /* SIGPIPE on stream socket */
+
 #ifndef strstr         /* glibc-2.1 declares this as a macro */
 extern char *strstr(); /* needed on sysV68 R3V7.1. */
 #endif /* strstr */
 
-int fetchlimit;                /* how often to tear down the server connection */
 int batchcount;                /* count of messages sent in current batch */
 flag peek_capable;     /* can we peek for better error recovery? */
 int pass;              /* how many times have we re-polled? */
+int stage;             /* where are we? */
 int phase;             /* where are we, for error-logging purposes? */
+int mytimeout;         /* value of nonreponse timeout */
 
 static const struct method *protocol;
 static jmp_buf restart;
@@ -87,7 +92,6 @@ static int tagnum;
 #define GENSYM (sprintf(tag, "A%04d", ++tagnum % TAGMOD), tag)
 
 static char shroud[PASSWORDLEN];       /* string to shroud in debug output */
-static int mytimeout;                  /* value of nonreponse timeout */
 static int timeoutcount;               /* count consecutive timeouts */
 static int msglen;                     /* actual message length */
 
@@ -108,10 +112,16 @@ void set_timeout(int timeleft)
 }
 
 static void timeout_handler (int signal)
-/* handle server-timeout SIGALRM signal */
+/* handle SIGALRM signal indicating a server timeout */
 {
     timeoutcount++;
-    longjmp(restart, 1);
+    longjmp(restart, THROW_TIMEOUT);
+}
+
+static void sigpipe_handler (int signal)
+/* handle SIGPIPE signal indicating a broken stream socket */
+{
+    longjmp(restart, THROW_SIGPIPE);
 }
 
 static int accept_count, reject_count;
@@ -221,6 +231,19 @@ static void find_server_names(const char *hdr,
     }
 }
 
+/*
+ * Return zero on a syntactically invalid address, nz on a valid one.
+ *
+ * This used to be strchr(a, '.'), but it turns out that lines like this
+ *
+ * Received: from punt-1.mail.demon.net by mailstore for markb@ordern.com
+ *          id 938765929:10:27223:2; Fri, 01 Oct 99 08:18:49 GMT
+ *
+ * are not uncommon.  So now we just check that the following token is
+ * not itself an email address.
+ */
+#define VALID_ADDRESS(a)       !strchr(a, '@')
+
 static char *parse_received(struct query *ctl, char *bufp)
 /* try to extract real address from the Received line */
 /* If a valid Received: line is found, we return the full address in
@@ -245,7 +268,7 @@ static char *parse_received(struct query *ctl, char *bufp)
     if (outlevel >= O_DEBUG)
        report(stdout, _("analyzing Received line:\n%s"), bufp);
 
-    /* search for whitepace-surrounded "by" followed by xxxx.yyyy */
+    /* search for whitepace-surrounded "by" followed by valid address */
     for (base = bufp;  ; base = ok + 2)
     {
        if (!(ok = strstr(base, "by")))
@@ -264,8 +287,8 @@ static char *parse_received(struct query *ctl, char *bufp)
                *tp++ = *sp;
            *tp = '\0';
 
-           /* look for embedded periods */
-           if (strchr(rbuf, '.'))
+           /* look for valid address */
+           if (VALID_ADDRESS(rbuf))
                break;
            else
                ok = sp - 1;    /* arrange to skip this token */
@@ -460,6 +483,13 @@ static int readheaders(int sock,
                }
            }
 
+           /*
+            * Decode MIME encoded headers. We MUST do this before
+            * looking at the Content-Type / Content-Transfer-Encoding
+            * headers (RFC 2046).
+            */
+           if (ctl->mimedecode)
+               UnMimeHeader(buf);
 
            line = (char *) realloc(line, strlen(line) + strlen(buf) +1);
 
@@ -499,7 +529,7 @@ static int readheaders(int sock,
            sizeticker += linelen;
            while (sizeticker >= SIZETICKER)
            {
-               if (!run.use_syslog)
+               if (!run.use_syslog && isatty(1))
                {
                    fputc('.', stdout);
                    fflush(stdout);
@@ -511,6 +541,33 @@ static int readheaders(int sock,
        /* we see an ordinary (non-header, non-message-delimiter line */
        has_nuls = (linelen != strlen(line));
 
+       /*
+        * When mail delivered to a multidrop mailbox on the server is
+        * addressed to multiple people on the client machine, there
+        * will be one copy left in the box for each recipient.  Thus,
+        * if the mail is addressed to N people, each recipient will
+        * get N copies.
+        *
+        * Foil this by suppressing all but one copy of a message with
+        * a given Message-ID.  Note: This implementation only catches
+        * runs of successive identical messages, but that should be
+        * good enough. 
+        * 
+        * The accept_count test ensures that multiple pieces of identical 
+        * email, each with a *single* addressee, won't be suppressed.
+        */
+       if (MULTIDROP(ctl) && accept_count > 1 && !strncasecmp(line, "Message-ID:", 11))
+       {
+           if (ctl->lastid && !strcasecmp(ctl->lastid, line))
+               return(PS_REFUSED);
+           else
+           {
+               if (ctl->lastid)
+                   free(ctl->lastid);
+               ctl->lastid = strdup(line);
+           }
+       }
+
        /*
         * The University of Washington IMAP server (the reference
         * implementation of IMAP4 written by Mark Crispin) relies
@@ -525,7 +582,11 @@ static int readheaders(int sock,
         * forward it to the user so he or she will have some clue
         * that things have gone awry.
         */
+#if INET6_ENABLE
+       if (strncmp(protocol->service, "pop2", 4))
+#else /* INET6_ENABLE */
        if (protocol->port != 109)
+#endif /* INET6_ENABLE */
 #endif /* POP2_ENABLE */
            if (num == 1 && !strncasecmp(line, "X-IMAP:", 7)) {
                free(line);
@@ -664,14 +725,15 @@ static int readheaders(int sock,
        else if (!strncasecmp("Resent-Sender:", line, 14))
            resent_sender_offs = (line - msgblk.headers);
 
-       else if (!strncasecmp("Message-Id:", buf, 11))
+#ifdef __UNUSED__
+       else if (!strncasecmp("Message-Id:", line, 11))
        {
            if (ctl->server.uidl)
            {
                char id[IDLEN+1];
 
-               buf[IDLEN+12] = 0;              /* prevent stack overflow */
-               sscanf(buf+12, "%s", id);
+               line[IDLEN+12] = 0;             /* prevent stack overflow */
+               sscanf(line+12, "%s", id);
                if (!str_find( &ctl->newsaved, num))
                {
                    struct idlist *new = save_str(&ctl->newsaved,id,UID_SEEN);
@@ -679,6 +741,7 @@ static int readheaders(int sock,
                }
            }
        }
+#endif /* __UNUSED__ */
 
        else if (!MULTIDROP(ctl))
            continue;
@@ -765,13 +828,6 @@ static int readheaders(int sock,
      * In fact we have to, as this will tell us where to forward to.
      */
 
-    /* Decode MIME encoded headers. We MUST do this before
-     * looking at the Content-Type / Content-Transfer-Encoding
-     * headers (RFC 2046).
-     */
-    if (ctl->mimedecode) {
-       UnMimeHeader(msgblk.headers);
-    }
     /* Check for MIME headers indicating possible 8-bit data */
     ctl->mimemsg = MimeBodyType(msgblk.headers, ctl->mimedecode);
 
@@ -844,7 +900,7 @@ static int readheaders(int sock,
             * We haven't extracted the envelope address.
             * So check all the "Resent-To" header addresses if 
             * they exist.  If and only if they don't, consider
-            * the "To" adresses.
+            * the "To" addresses.
             */
            register struct addrblk *nextptr;
            if (resent_to_addrchain) {
@@ -991,7 +1047,7 @@ static int readheaders(int sock,
        free_str_list(&msgblk.recipients);
        return(PS_IOERR);
     }
-    else if (!run.use_syslog && outlevel >= O_VERBOSE)
+    else if ((run.poll_interval == 0 || nodetach) && outlevel >= O_VERBOSE && isatty(2))
        fputs("#", stderr);
 
     /* write error notifications */
@@ -1011,7 +1067,7 @@ static int readheaders(int sock,
                for (idp = msgblk.recipients; idp; idp = idp->next)
                    if (idp->val.status.mark == XMIT_REJECT)
                        break;
-               sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name\n"), idp->id);
+               sprintf(errhd+strlen(errhd), _("recipient address %s didn't match any local name"), idp->id);
            }
        }
 
@@ -1074,7 +1130,16 @@ static int readbody(int sock, struct query *ctl, flag forward, int len)
     unsigned char *inbufp = buf;
     flag issoftline = FALSE;
 
-    /* pass through the text lines */
+    /*
+     * Pass through the text lines in the body.
+     *
+     * Yes, this wants to be ||, not &&.  The problem is that in the most
+     * important delimited protocol, POP3, the length is not reliable.
+     * As usual, the problem is Microsoft brain damage; see FAQ item S2.
+     * So, for delimited protocols we need to ignore the length here and
+     * instead drop out of the loop with a break statement when we see
+     * the message delimiter.
+     */
     while (protocol->delimited || len > 0)
     {
        set_timeout(mytimeout);
@@ -1092,7 +1157,7 @@ static int readbody(int sock, struct query *ctl, flag forward, int len)
            sizeticker += linelen;
            while (sizeticker >= SIZETICKER)
            {
-               if (!run.use_syslog && outlevel > O_SILENT)
+               if ((run.poll_interval == 0 || nodetach) && outlevel > O_SILENT && isatty(1))
                {
                    fputc('.', stdout);
                    fflush(stdout);
@@ -1104,12 +1169,14 @@ static int readbody(int sock, struct query *ctl, flag forward, int len)
 
        /* check for end of message */
        if (protocol->delimited && *inbufp == '.')
+       {
            if (inbufp[1] == '\r' && inbufp[2] == '\n' && inbufp[3] == '\0')
                break;
            else if (inbufp[1] == '\n' && inbufp[2] == '\0')
                break;
            else
                msglen--;       /* subtract the size of the dot escape */
+       }
 
        msglen += linelen;
 
@@ -1148,8 +1215,11 @@ static int readbody(int sock, struct query *ctl, flag forward, int len)
                release_sink(ctl);
                return(PS_IOERR);
            }
-           else if (outlevel >= O_VERBOSE)
-               fputc('*', stderr);
+           else if (outlevel >= O_VERBOSE && isatty(1))
+           {
+               fputc('*', stdout);
+               fflush(stdout);
+           }
        }
     }
 
@@ -1161,7 +1231,7 @@ int
 kerberos_auth (socket, canonical) 
 /* authenticate to the server host using Kerberos V4 */
 int socket;            /* socket to server host */
-#ifdef __FreeBSD__
+#if defined(__FreeBSD__) || defined(__OpenBSD__)
 char *canonical;       /* server name */
 #else
 const char *canonical; /* server name */
@@ -1244,11 +1314,18 @@ const char *canonical;  /* server name */
     krb5_auth_con_free(context, auth_context);
 
     if (retval) {
+#ifdef HEIMDAL
+      if (err_ret && err_ret->e_text) {
+          report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
+                 error_message(retval),
+                 err_ret->e_text);
+#else
       if (err_ret && err_ret->text.length) {
           report(stderr, _("krb5_sendauth: %s [server says '%*s'] \n"),
                 error_message(retval),
                 err_ret->text.length,
                 err_ret->text.data);
+#endif
          krb5_free_error(context, err_ret);
       } else
           report(stderr, "krb5_sendauth: %s\n", error_message(retval));
@@ -1340,7 +1417,7 @@ static void send_size_warnings(struct query *ctl)
            nbr = current->val.status.mark;
            size = atoi(current->id);
            stuff_warning(ctl, 
-                   _("\t%d msg %d octets long skipped by fetchmail.\n"),
+                   _("\t%d msg %d octets long skipped by fetchmail.\r\n"),
                    nbr, size);
        }
        current->val.status.num++;
@@ -1354,75 +1431,39 @@ static void send_size_warnings(struct query *ctl)
 #undef OVERHD
 }
 
-int do_protocol(ctl, proto)
+static int do_session(ctl, proto, maxfetch)
 /* retrieve messages from server using given protocol method table */
 struct query *ctl;             /* parsed options with merged-in defaults */
 const struct method *proto;    /* protocol method table */
+const int maxfetch;            /* maximum number of messages to fetch */
 {
-    int ok, js;
+    int js;
 #ifdef HAVE_VOLATILE
-    volatile int sock = -1;    /* pacifies -Wall */
+    volatile int ok, mailserver_socket = -1;   /* pacifies -Wall */
 #else
-    int sock = -1;
+    int ok, mailserver_socket = -1;
 #endif /* HAVE_VOLATILE */
     const char *msg;
-    void (*sigsave)(int);
+    void (*pipesave)(int);
+    void (*alrmsave)(int);
     struct idlist *current=NULL, *tmp=NULL;
 
     protocol = proto;
     ctl->server.base_protocol = protocol;
 
-#ifndef KERBEROS_V4
-    if (ctl->server.preauthenticate == A_KERBEROS_V4)
-    {
-       report(stderr, _("Kerberos V4 support not linked.\n"));
-       return(PS_ERROR);
-    }
-#endif /* KERBEROS_V4 */
-
-#ifndef KERBEROS_V5
-    if (ctl->server.preauthenticate == A_KERBEROS_V5)
-    {
-       report(stderr, _("Kerberos V5 support not linked.\n"));
-       return(PS_ERROR);
-    }
-#endif /* KERBEROS_V5 */
-
-    /* lacking methods, there are some options that may fail */
-    if (!proto->is_old)
-    {
-       /* check for unsupported options */
-       if (ctl->flush) {
-           report(stderr,
-                   _("Option --flush is not supported with %s\n"),
-                   proto->name);
-           return(PS_SYNTAX);
-       }
-       else if (ctl->fetchall) {
-           report(stderr,
-                   _("Option --all is not supported with %s\n"),
-                   proto->name);
-           return(PS_SYNTAX);
-       }
-    }
-    if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
-    {
-       report(stderr,
-               _("Option --limit is not supported with %s\n"),
-               proto->name);
-       return(PS_SYNTAX);
-    }
-
     pass = 0;
     tagnum = 0;
     tag[0] = '\0';     /* nuke any tag hanging out from previous query */
     ok = 0;
 
     /* set up the server-nonresponse timeout */
-    sigsave = signal(SIGALRM, timeout_handler);
+    alrmsave = signal(SIGALRM, timeout_handler);
     mytimeout = ctl->server.timeout;
 
-    if ((js = setjmp(restart)) == 1)
+    /* set up the broken-pipe timeout */
+    pipesave = signal(SIGPIPE, sigpipe_handler);
+
+    if ((js = setjmp(restart)))
     {
 #ifdef HAVE_SIGPROCMASK
        /*
@@ -1440,68 +1481,80 @@ const struct method *proto;     /* protocol method table */
        sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
 #endif /* HAVE_SIGPROCMASK */
 
-       if (phase == OPEN_WAIT)
-           report(stdout,
-                 _("timeout after %d seconds waiting to connect to server %s.\n"),
-                 ctl->server.timeout, ctl->server.pollname);
-       else if (phase == SERVER_WAIT)
-           report(stdout,
-                 _("timeout after %d seconds waiting for server %s.\n"),
-                 ctl->server.timeout, ctl->server.pollname);
-       else if (phase == FORWARDING_WAIT)
-           report(stdout,
-                 _("timeout after %d seconds waiting for %s.\n"),
-                 ctl->server.timeout,
-                 ctl->mda ? "MDA" : "SMTP");
-       else if (phase == LISTENER_WAIT)
+       if (js == THROW_SIGPIPE)
+       {
            report(stdout,
-                 _("timeout after %d seconds waiting for listener to respond.\n"));
-       else
-           report(stdout, _("timeout after %d seconds.\n"), ctl->server.timeout);
+                  _("SIGPIPE thrown from an MDA or a stream socket error\n"));
+           ok = PS_SOCKET;
+           goto cleanUp;
+       }
+       else if (js == THROW_TIMEOUT)
+       {
+           if (phase == OPEN_WAIT)
+               report(stdout,
+                      _("timeout after %d seconds waiting to connect to server %s.\n"),
+                      ctl->server.timeout, ctl->server.pollname);
+           else if (phase == SERVER_WAIT)
+               report(stdout,
+                      _("timeout after %d seconds waiting for server %s.\n"),
+                      ctl->server.timeout, ctl->server.pollname);
+           else if (phase == FORWARDING_WAIT)
+               report(stdout,
+                      _("timeout after %d seconds waiting for %s.\n"),
+                      ctl->server.timeout,
+                      ctl->mda ? "MDA" : "SMTP");
+           else if (phase == LISTENER_WAIT)
+               report(stdout,
+                      _("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
+           else
+               report(stdout, 
+                      _("timeout after %d seconds.\n"), ctl->server.timeout);
 
-       release_sink(ctl);
-       if (ctl->smtp_socket != -1)
-           close(ctl->smtp_socket);
-       if (sock != -1)
-           SockClose(sock);
+           /*
+            * If we've exceeded our threshold for consecutive timeouts, 
+            * try to notify the user, then mark the connection wedged.
+            * Don't do this if the connection can idle, though; idle
+            * timeouts just mean the frequency of mail is low.
+            */
+           if (timeoutcount > MAX_TIMEOUTS 
+               && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
+           {
+               stuff_warning(ctl,
+                             _("Subject: fetchmail sees repeated timeouts\r\n"));
+               stuff_warning(ctl,
+                             _("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\r\n"), 
+                             MAX_TIMEOUTS,
+                             ctl->remotename,
+                             ctl->server.truename);
+               stuff_warning(ctl, 
+    _("This could mean that your mailserver is stuck, or that your SMTP\r\n" \
+    "server is wedged, or that your mailbox file on the server has been\r\n" \
+    "corrupted by a server error.  You can run `fetchmail -v -v' to\r\n" \
+    "diagnose the problem.\r\n\r\n" \
+    "Fetchmail won't poll this mailbox again until you restart it.\r\n"));
+               close_warning_by_mail(ctl, (struct msgblk *)NULL);
+               ctl->wedged = TRUE;
+           }
 
-       /*
-        * If we've exceeded our threshold for consecutive timeouts, 
-        * try to notify the user, then mark the connection wedged.
-        */
-       if (timeoutcount > MAX_TIMEOUTS 
-                       && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
-       {
-           stuff_warning(ctl,
-                         _("Subject: fetchmail sees repeated timeouts\r\n"));
-           stuff_warning(ctl,
-                         _("Fetchmail saw more than %d timouts while attempting to get mail from %s@%s.\n"), 
-                         MAX_TIMEOUTS,
-                         ctl->remotename,
-                         ctl->server.truename);
-           stuff_warning(ctl, 
-                         _("This could mean that your mailserver is stuck, or that your SMTP listener"));
-           stuff_warning(ctl, 
-                         _("is wedged, or that your mailbox file on the server has been corrupted by"));
-           stuff_warning(ctl, 
-                         _("a server error.  You can run `fetchmail -v -v' to diagnose the problem."));
-           stuff_warning(ctl,
-                         _("Fetchmail won't poll this mailbox again until you restart it."));
-           close_warning_by_mail(ctl, (struct msgblk *)NULL);
-           ctl->wedged = TRUE;
+           ok = PS_ERROR;
        }
 
-       ok = PS_ERROR;
+       /* try to clean up all streams */
+       release_sink(ctl);
+       if (ctl->smtp_socket != -1)
+           SockClose(ctl->smtp_socket);
+       if (mailserver_socket != -1)
+           SockClose(mailserver_socket);
     }
     else
     {
-       char buf[POPBUFSIZE+1], *realhost;
+       char buf[MSGBUFSIZE+1], *realhost;
        int len, num, count, new, bytes, deletions = 0, *msgsizes = NULL;
-#if INET6
+#if INET6_ENABLE
        int fetches, dispatches, oldphase;
-#else /* INET6 */
+#else /* INET6_ENABLE */
        int port, fetches, dispatches, oldphase;
-#endif /* INET6 */
+#endif /* INET6_ENABLE */
        struct idlist *idp;
 
        /* execute pre-initialization command, if any */
@@ -1517,19 +1570,28 @@ const struct method *proto;     /* protocol method table */
        oldphase = phase;
        phase = OPEN_WAIT;
        set_timeout(mytimeout);
-#if !INET6
+#if !INET6_ENABLE
+#ifdef SSL_ENABLE
+       port = ctl->server.port ? ctl->server.port : ( ctl->use_ssl ? protocol->sslport : protocol->port );
+#else
        port = ctl->server.port ? ctl->server.port : protocol->port;
-#endif /* !INET6 */
+#endif
+#endif /* !INET6_ENABLE */
        realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
-#if INET6
-       if ((sock = SockOpen(realhost, 
+
+       /* allow time for the port to be set up if we have a plugin */
+       if (ctl->server.plugin)
+           (void)sleep(1);
+#if INET6_ENABLE
+       if ((mailserver_socket = SockOpen(realhost, 
                             ctl->server.service ? ctl->server.service : protocol->service,
                             ctl->server.netsec, ctl->server.plugin)) == -1)
-#else /* INET6 */
-       if ((sock = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
-#endif /* INET6 */
+#else /* INET6_ENABLE */
+       if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
+#endif /* INET6_ENABLE */
        {
-#if !INET6
+           char        errbuf[BUFSIZ];
+#if !INET6_ENABLE
            int err_no = errno;
 #ifdef HAVE_RES_SEARCH
            if (err_no != 0 && h_errno != 0)
@@ -1540,31 +1602,49 @@ const struct method *proto;     /* protocol method table */
             * in daemon mode but the connection to the outside world
             * is down.
             */
-           if (err_no == EHOSTUNREACH && run.poll_interval)
-               goto ehostunreach;
-
-           report_build(stderr, _("fetchmail: %s connection to %s failed"), 
-                        protocol->name, ctl->server.pollname);
-#ifdef HAVE_RES_SEARCH
-           if (h_errno != 0)
+           if (!((err_no == EHOSTUNREACH || err_no == ENETUNREACH) 
+                 && run.poll_interval))
            {
-               if (h_errno == HOST_NOT_FOUND)
-                   report_complete(stderr, _(": host is unknown\n"));
-               else if (h_errno == NO_ADDRESS)
-                   report_complete(stderr, _(": name is valid but has no IP address\n"));
-               else if (h_errno == NO_RECOVERY)
-                   report_complete(stderr, _(": unrecoverable name server error\n"));
-               else if (h_errno == TRY_AGAIN)
-                   report_complete(stderr, _(": temporary name server error\n"));
+               report_build(stderr, _("fetchmail: %s connection to %s failed"), 
+                            protocol->name, ctl->server.pollname);
+#ifdef HAVE_RES_SEARCH
+               if (h_errno != 0)
+               {
+                   if (h_errno == HOST_NOT_FOUND)
+                       strcpy(errbuf, _("host is unknown."));
+                   else if (h_errno == NO_ADDRESS)
+                       strcpy(errbuf, _("name is valid but has no IP address."));
+                   else if (h_errno == NO_RECOVERY)
+                       strcpy(errbuf, _("unrecoverable name server error."));
+                   else if (h_errno == TRY_AGAIN)
+                       strcpy(errbuf, _("temporary name server error."));
+                   else
+                       sprintf(errbuf, _("unknown DNS error %d."), h_errno);
+               }
                else
-                   report_complete(stderr, _(": unknown DNS error %d\n"), h_errno);
-           }
-           else
 #endif /* HAVE_RES_SEARCH */
-               report_complete(stderr, ": %s\n", strerror(err_no));
-
-       ehostunreach:
-#endif /* INET6 */
+                   strcpy(errbuf, strerror(err_no));
+               report_complete(stderr, ": %s\n", errbuf);
+
+#ifdef __UNUSED
+               /* 
+                * Don't use this.  It was an attempt to address Debian bug
+                * #47143 (Notify user by mail when pop server nonexistent).
+                * Trouble is, that doesn't work; you trip over the case 
+                * where your SLIP or PPP link is down...
+                */
+               /* warn the system administrator */
+               if (open_warning_by_mail(ctl, (struct msgblk *)NULL) == 0)
+               {
+#define OPENFAIL       "Subject: Fetchmail unreachable-server warning.\r\n\r\nFetchmail could not reach the mail server %s:"
+                   stuff_warning(ctl, OPENFAIL, ctl->server.pollname);
+                   stuff_warning(ctl, errbuf, ctl->server.pollname);
+                   close_warning_by_mail(ctl, (struct msgblk *)NULL);
+#undef OPENFAIL
+               }
+#endif
+           }
+#endif /* INET6_ENABLE */
            ok = PS_SOCKET;
            set_timeout(0);
            phase = oldphase;
@@ -1573,11 +1653,22 @@ const struct method *proto;     /* protocol method table */
        set_timeout(0);
        phase = oldphase;
 
+#ifdef SSL_ENABLE
+       /* perform initial SSL handshake on open connection */
+       /* Note:  We pass the realhost name over for certificate
+               verification.  We may want to make this configurable */
+       if (ctl->use_ssl && SSLOpen(mailserver_socket,ctl->sslkey,ctl->sslcert,realhost) == -1) 
+       {
+           report(stderr, "SSL connection failed.");
+           goto closeUp;
+       }
+#endif
+
 #ifdef KERBEROS_V4
        if (ctl->server.preauthenticate == A_KERBEROS_V4)
        {
            set_timeout(mytimeout);
-           ok = kerberos_auth(sock, ctl->server.truename);
+           ok = kerberos_auth(mailserver_socket, ctl->server.truename);
            set_timeout(0);
            if (ok != 0)
                goto cleanUp;
@@ -1588,7 +1679,7 @@ const struct method *proto;       /* protocol method table */
        if (ctl->server.preauthenticate == A_KERBEROS_V5)
        {
            set_timeout(mytimeout);
-           ok = kerberos5_auth(sock, ctl->server.truename);
+           ok = kerberos5_auth(mailserver_socket, ctl->server.truename);
            set_timeout(0);
            if (ok != 0)
                goto cleanUp;
@@ -1596,29 +1687,28 @@ const struct method *proto;     /* protocol method table */
 #endif /* KERBEROS_V5 */
 
        /* accept greeting message from mail server */
-       ok = (protocol->parse_response)(sock, buf);
+       ok = (protocol->parse_response)(mailserver_socket, buf);
        if (ok != 0)
            goto cleanUp;
 
        /* try to get authorized to fetch mail */
+       stage = STAGE_GETAUTH;
        if (protocol->getauth)
        {
            if (protocol->password_canonify)
-               (protocol->password_canonify)(shroud, ctl->password);
+               (protocol->password_canonify)(shroud, ctl->password, PASSWORDLEN);
            else
                strcpy(shroud, ctl->password);
 
-           ok = (protocol->getauth)(sock, ctl, buf);
+           ok = (protocol->getauth)(mailserver_socket, ctl, buf);
            if (ok != 0)
            {
                if (ok == PS_LOCKBUSY)
                    report(stderr, _("Lock-busy error on %s@%s\n"),
                          ctl->remotename,
                          ctl->server.truename);
-               else
+               else if (ok == PS_AUTHFAIL)
                {
-                   if (ok == PS_ERROR)
-                       ok = PS_AUTHFAIL;
                    report(stderr, _("Authorization failure on %s@%s\n"), 
                          ctl->remotename,
                          ctl->server.truename);
@@ -1626,26 +1716,33 @@ const struct method *proto;     /* protocol method table */
                    /*
                     * If we're running in background, try to mail the
                     * calling user a heads-up about the authentication 
-                    * failure the first time it happens.
+                    * failure once it looks like this isn't a fluke 
+                    * due to the server being temporarily inaccessible.
                     */
                    if (run.poll_interval
-                       && !ctl->wedged 
+                       && ctl->authfailcount++ > MAX_AUTHFAILS 
                        && !open_warning_by_mail(ctl, (struct msgblk *)NULL))
                    {
                        stuff_warning(ctl,
-                              _("Subject: fetchmail authentication failed\r\n"));
+                           _("Subject: fetchmail authentication failed\r\n"));
                        stuff_warning(ctl,
-                               _("Fetchmail could not get mail from %s@%s.\n"), 
-                               ctl->remotename,
-                               ctl->server.truename);
+                           _("Fetchmail could not get mail from %s@%s.\r\n"), 
+                           ctl->remotename,
+                           ctl->server.truename);
                        stuff_warning(ctl, 
-                              _("The attempt to get authorization failed."));
-                       stuff_warning(ctl, 
-                              _("This probably means your password is invalid."));
+    _("The attempt to get authorization failed.\r\n" \
+    "This probably means your password is invalid, but POP3 servers have\r\n" \
+    "other failure modes that fetchmail cannot distinguish from this\r\n" \
+    "because they don't send useful error messages on login failure.\r\n"));
                        close_warning_by_mail(ctl, (struct msgblk *)NULL);
                        ctl->wedged = TRUE;
                    }
                }
+               else
+                   report(stderr, _("Unknown login or authentication error on %s@%s\n"),
+                         ctl->remotename,
+                         ctl->server.truename);
+                   
                goto cleanUp;
            }
        }
@@ -1660,14 +1757,20 @@ const struct method *proto;     /* protocol method table */
                dispatches = 0;
                ++pass;
 
+               /* reset timeout, in case we did an IDLE */
+               mytimeout = ctl->server.timeout;
+
                if (outlevel >= O_DEBUG)
+               {
                    if (idp->id)
                        report(stdout, _("selecting or re-polling folder %s\n"), idp->id);
                    else
                        report(stdout, _("selecting or re-polling default folder\n"));
+               }
 
                /* compute # of messages and number of new messages waiting */
-               ok = (protocol->getrange)(sock, ctl, idp->id, &count, &new, &bytes);
+               stage = STAGE_GETRANGE;
+               ok = (protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
                if (ok != 0)
                    goto cleanUp;
 
@@ -1679,6 +1782,7 @@ const struct method *proto;       /* protocol method table */
                    (void) sprintf(buf, _("%s at %s"),
                                   ctl->remotename, ctl->server.truename);
                if (outlevel > O_SILENT)
+               {
                    if (count == -1)            /* only used for ETRN */
                        report(stdout, _("Polling %s\n"), ctl->server.truename);
                    else if (count != 0)
@@ -1703,6 +1807,7 @@ const struct method *proto;       /* protocol method table */
                        if (pass == 1 && (run.poll_interval == 0 || outlevel >= O_VERBOSE))
                            report(stdout, _("No mail for %s\n"), buf); 
                    }
+               }
 
                /* very important, this is where we leave the do loop */ 
                if (count == 0)
@@ -1713,7 +1818,12 @@ const struct method *proto;      /* protocol method table */
                    if (new == -1 || ctl->fetchall)
                        new = count;
                    fetches = new;      /* set error status ccorrectly */
-                   goto no_error;
+                   /*
+                    * There used to be a `got noerror' here, but this
+                    * prevneted checking of multiple folders.  This
+                    * comment is a reminder in case I introduced some
+                    * subtle bug by removing it...
+                    */
                }
                else if (count > 0)
                {    
@@ -1750,7 +1860,7 @@ const struct method *proto;       /* protocol method table */
 
                    /* 
                     * We need the size of each message before it's
-                    * loaded in order to pass via the ESMTP SIZE
+                    * loaded in order to pass it to the ESMTP SIZE
                     * option.  If the protocol has a getsizes method,
                     * we presume this means it doesn't get reliable
                     * sizes from message fetch responses.
@@ -1763,7 +1873,8 @@ const struct method *proto;       /* protocol method table */
                        for (i = 0; i < count; i++)
                            msgsizes[i] = -1;
 
-                       ok = (proto->getsizes)(sock, count, msgsizes);
+                       stage = STAGE_GETSIZES;
+                       ok = (proto->getsizes)(mailserver_socket, count, msgsizes);
                        if (ok != 0)
                            goto cleanUp;
 
@@ -1776,11 +1887,12 @@ const struct method *proto;     /* protocol method table */
                    }
 
                    /* read, forward, and delete messages */
+                   stage = STAGE_FETCH;
                    for (num = 1; num <= count; num++)
                    {
                        flag toolarge = NUM_NONZERO(ctl->limit)
                            && msgsizes && (msgsizes[num-1] > ctl->limit);
-                       flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(sock,ctl,num));
+                       flag oldmsg = (!new) || (protocol->is_old && (protocol->is_old)(mailserver_socket,ctl,num));
                        flag fetch_it = !toolarge 
                            && (ctl->fetchall || force_retrieval || !oldmsg);
                        flag suppress_delete = FALSE;
@@ -1802,12 +1914,15 @@ const struct method *proto;     /* protocol method table */
                        {
                            if (outlevel >= O_VERBOSE)
                                report(stdout, 
-                                     _("Skipping message %d, length -1"),
-                                     num - 1);
+                                     _("Skipping message %d, length -1\n"),
+                                     num);
                            continue;
                        }
 
-                       /* we may want to reject this message if it's old */
+                       /*
+                        * We may want to reject this message if it's old
+                        * or oversized, and we're not forcing retrieval.
+                        */
                        if (!fetch_it)
                        {
                            if (outlevel > O_SILENT)
@@ -1867,7 +1982,7 @@ const struct method *proto;       /* protocol method table */
                            flag wholesize = !protocol->fetch_body;
 
                            /* request a message */
-                           ok = (protocol->fetch_headers)(sock,ctl,num, &len);
+                           ok = (protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
                            if (ok != 0)
                                goto cleanUp;
 
@@ -1896,7 +2011,7 @@ const struct method *proto;       /* protocol method table */
                             * Read the message headers and ship them to the
                             * output sink.  
                             */
-                           ok = readheaders(sock, len, msgsizes[num-1],
+                           ok = readheaders(mailserver_socket, len, msgsizes[num-1],
                                             ctl, num);
                            if (ok == PS_RETAINED)
                                suppress_forward = retained = TRUE;
@@ -1919,19 +2034,28 @@ const struct method *proto;     /* protocol method table */
                             */
                            if (protocol->fetch_body && !suppress_readbody) 
                            {
-                               if (outlevel >= O_VERBOSE)
+                               if (outlevel >= O_VERBOSE && isatty(1))
                                {
                                    fputc('\n', stdout);
                                    fflush(stdout);
                                }
 
-                               if ((ok = (protocol->trail)(sock, ctl, num)))
+                               if ((ok = (protocol->trail)(mailserver_socket, ctl, num)))
                                    goto cleanUp;
                                len = 0;
                                if (!suppress_forward)
                                {
-                                   if ((ok=(protocol->fetch_body)(sock,ctl,num,&len)))
+                                   if ((ok=(protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
                                        goto cleanUp;
+                                    /*
+                                     * Work around a bug in Novell's
+                                    * broken GroupWise IMAP server;
+                                     * its body FETCH response is missing
+                                    * the required length for the data
+                                    * string.  This violates RFC2060.
+                                     */
+                                    if (len == -1)
+                                       len = msgsizes[num-1] - msglen;
                                    if (outlevel > O_SILENT && !wholesize)
                                        report_complete(stdout,
                                               _(" (%d body octets) "), len);
@@ -1951,7 +2075,7 @@ const struct method *proto;       /* protocol method table */
                                }
                                else
                                {
-                                 ok = readbody(sock,
+                                 ok = readbody(mailserver_socket,
                                                ctl,
                                                !suppress_forward,
                                                len);
@@ -1964,13 +2088,13 @@ const struct method *proto;     /* protocol method table */
                                /* tell server we got it OK and resynchronize */
                                if (protocol->trail)
                                {
-                                   if (outlevel >= O_VERBOSE)
+                                   if (outlevel >= O_VERBOSE && isatty(1))
                                    {
                                        fputc('\n', stdout);
                                        fflush(stdout);
                                    }
 
-                                   ok = (protocol->trail)(sock, ctl, num);
+                                   ok = (protocol->trail)(mailserver_socket, ctl, num);
                                    if (ok != 0)
                                        goto cleanUp;
                                }
@@ -2053,7 +2177,7 @@ const struct method *proto;       /* protocol method table */
                            deletions++;
                            if (outlevel > O_SILENT) 
                                report_complete(stdout, _(" flushed\n"));
-                           ok = (protocol->delete)(sock, ctl, num);
+                           ok = (protocol->delete)(mailserver_socket, ctl, num);
                            if (ok != 0)
                                goto cleanUp;
 #ifdef POP3_ENABLE
@@ -2064,12 +2188,12 @@ const struct method *proto;     /* protocol method table */
                            report_complete(stdout, _(" not flushed\n"));
 
                        /* perhaps this as many as we're ready to handle */
-                       if (NUM_NONZERO(ctl->fetchlimit)
-                                       && ctl->fetchlimit <= fetches)
+                       if (maxfetch && maxfetch <= fetches && fetches < count)
                        {
-                           report(stdout, _("fetchlimit reached; %d messages left on server\n"),
-                                 count - fetches);
-                           goto no_error;
+                           report(stdout, _("fetchlimit %d reached; %d messages left on server\n"),
+                                 maxfetch, count - fetches);
+                           ok = PS_MAXFETCH;
+                           goto cleanUp;
                        }
                    }
 
@@ -2082,8 +2206,8 @@ const struct method *proto;       /* protocol method table */
                }
            } while
                  /*
-                  * Only re-poll if we had some actual forwards, allowed
-                  * deletions and had no errors.
+                  * Only re-poll if we either had some actual forwards and 
+                  * either allowed deletions and had no errors.
                   * Otherwise it is far too easy to get into infinite loops.
                   */
                  (dispatches && protocol->retry && !ctl->keep && !ctl->errcount);
@@ -2091,21 +2215,24 @@ const struct method *proto;     /* protocol method table */
 
    no_error:
        /* ordinary termination with no errors -- officially log out */
-       ok = (protocol->logout_cmd)(sock, ctl);
+       ok = (protocol->logout_cmd)(mailserver_socket, ctl);
        /*
         * Hmmmm...arguably this would be incorrect if we had fetches but
         * no dispatches (due to oversized messages, etc.)
         */
        if (ok == 0)
            ok = (fetches > 0) ? PS_SUCCESS : PS_NOMAIL;
-       SockClose(sock);
+       SockClose(mailserver_socket);
        goto closeUp;
 
     cleanUp:
        /* we only get here on error */
        if (ok != 0 && ok != PS_SOCKET)
-           (protocol->logout_cmd)(sock, ctl);
-       SockClose(sock);
+       {
+           stage = STAGE_LOGOUT;
+           (protocol->logout_cmd)(mailserver_socket, ctl);
+       }
+       SockClose(mailserver_socket);
     }
 
     msg = (const char *)NULL;  /* sacrifice to -Wall */
@@ -2139,12 +2266,13 @@ const struct method *proto;     /* protocol method table */
        msg = _("DNS lookup");
        break;
     case PS_UNDEFINED:
-       report(stderr, _("undefined\n"));
+       report(stderr, _("undefined error\n"));
        break;
     }
+    /* no report on PS_MAXFETCH or PS_UNDEFINED */
     if (ok==PS_SOCKET || ok==PS_AUTHFAIL || ok==PS_SYNTAX 
                || ok==PS_IOERR || ok==PS_ERROR || ok==PS_PROTOCOL 
-               || ok==PS_LOCKBUSY || ok==PS_SMTP)
+               || ok==PS_LOCKBUSY || ok==PS_SMTP || ok==PS_DNS)
        report(stderr, _("%s error while fetching from %s\n"), msg, ctl->server.pollname);
 
 closeUp:
@@ -2156,10 +2284,104 @@ closeUp:
            ok = PS_SYNTAX;
     }
 
-    signal(SIGALRM, sigsave);
+    signal(SIGALRM, alrmsave);
+    signal(SIGPIPE, pipesave);
     return(ok);
 }
 
+int do_protocol(ctl, proto)
+/* retrieve messages from server using given protocol method table */
+struct query *ctl;             /* parsed options with merged-in defaults */
+const struct method *proto;    /* protocol method table */
+{
+    int        ok;
+
+#ifndef KERBEROS_V4
+    if (ctl->server.preauthenticate == A_KERBEROS_V4)
+    {
+       report(stderr, _("Kerberos V4 support not linked.\n"));
+       return(PS_ERROR);
+    }
+#endif /* KERBEROS_V4 */
+
+#ifndef KERBEROS_V5
+    if (ctl->server.preauthenticate == A_KERBEROS_V5)
+    {
+       report(stderr, _("Kerberos V5 support not linked.\n"));
+       return(PS_ERROR);
+    }
+#endif /* KERBEROS_V5 */
+
+    /* lacking methods, there are some options that may fail */
+    if (!proto->is_old)
+    {
+       /* check for unsupported options */
+       if (ctl->flush) {
+           report(stderr,
+                   _("Option --flush is not supported with %s\n"),
+                   proto->name);
+           return(PS_SYNTAX);
+       }
+       else if (ctl->fetchall) {
+           report(stderr,
+                   _("Option --all is not supported with %s\n"),
+                   proto->name);
+           return(PS_SYNTAX);
+       }
+    }
+    if (!proto->getsizes && NUM_SPECIFIED(ctl->limit))
+    {
+       report(stderr,
+               _("Option --limit is not supported with %s\n"),
+               proto->name);
+       return(PS_SYNTAX);
+    }
+
+    /*
+     * If no expunge limit or we do expunges within the driver,
+     * then just do one session, passing in any fetchlimit.
+     */
+    if (proto->retry || !NUM_SPECIFIED(ctl->expunge))
+       return(do_session(ctl, proto, NUM_VALUE_OUT(ctl->fetchlimit)));
+    /*
+     * There's an expunge limit, and it isn't handled in the driver itself.
+     * OK; do multiple sessions, each fetching a limited # of messages.
+     * Stop if the total count of retrieved messages exceeds ctl->fetchlimit
+     * (if it was nonzero).
+     */
+    else
+    {
+       int totalcount = 0; 
+       int lockouts   = 0;
+       int expunge    = NUM_VALUE_OUT(ctl->expunge);
+       int fetchlimit = NUM_VALUE_OUT(ctl->fetchlimit);
+
+       do {
+           ok = do_session(ctl, proto, expunge);
+           totalcount += expunge;
+           if (NUM_SPECIFIED(ctl->fetchlimit) && totalcount >= fetchlimit)
+               break;
+           if (ok != PS_LOCKBUSY)
+               lockouts = 0;
+           else if (lockouts >= MAX_LOCKOUTS)
+               break;
+           else /* ok == PS_LOCKBUSY */
+           {
+               /*
+                * Allow time for the server lock to release.  if we
+                * don't do this, we'll often hit a locked-mailbox
+                * condition and fail.
+                */
+               lockouts++;
+               sleep(3);
+           }
+       } while
+           (ok == PS_MAXFETCH || ok == PS_LOCKBUSY);
+
+       return(ok);
+    }
+}
+
 #if defined(HAVE_STDARG_H)
 void gen_send(int sock, const char *fmt, ... )
 #else