]> Pileus Git - ~andy/fetchmail/blobdiff - driver.c
Before showdots,
[~andy/fetchmail] / driver.c
index c934ea74739ffff5b23fe1066bca86402b3d3452..e0b86d6cd056d1c106611599f5258db85782e2b5 100644 (file)
--- a/driver.c
+++ b/driver.c
 #include  <sys/time.h>
 #include  <signal.h>
 
+#ifdef HAVE_NET_SOCKET_H
+#include <net/socket.h>
+#endif
+
 #ifdef HAVE_RES_SEARCH
 #include <netdb.h>
 #include "mx.h"
@@ -80,7 +84,9 @@ extern char *strstr();        /* needed on sysV68 R3V7.1. */
 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;
@@ -90,14 +96,13 @@ 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 */
 
 void set_timeout(int timeleft)
 /* reset the nonresponse-timeout */
 {
-#ifndef __EMX__
+#if !defined(__EMX__) && !defined(__BEOS__) 
     struct itimerval ntimeout;
 
     if (timeleft == 0)
@@ -429,7 +434,7 @@ static int readheaders(int sock,
     int                        from_offs, reply_to_offs, resent_from_offs;
     int                        app_from_offs, sender_offs, resent_sender_offs;
     int                        env_offs;
-    char               *received_for, *rcv, *cp;
+    char               *received_for, *rcv, *cp, *delivered_to;
     int                n, linelen, oldlen, ch, remaining, skipcount;
     struct idlist      *idp;
     flag               no_local_matches = FALSE;
@@ -443,7 +448,17 @@ static int readheaders(int sock,
 
     /* read message headers */
     msgblk.reallen = reallen;
-    msgblk.headers = received_for = NULL;
+
+    /*
+     * We used to free the header block unconditionally at the end of 
+     * readheaders, but it turns out that if close_sink() hits an error
+     * condition the code for sending bouncemail will actually look
+     * at the freed storage and coredump...
+     */
+    if (msgblk.headers)
+       free(msgblk.headers);
+
+    msgblk.headers = received_for = delivered_to = NULL;
     from_offs = reply_to_offs = resent_from_offs = app_from_offs = 
        sender_offs = resent_sender_offs = env_offs = -1;
     oldlen = 0;
@@ -528,7 +543,7 @@ static int readheaders(int sock,
            sizeticker += linelen;
            while (sizeticker >= SIZETICKER)
            {
-               if (!run.use_syslog)
+               if (!run.use_syslog && !isafile(1))
                {
                    fputc('.', stdout);
                    fflush(stdout);
@@ -545,20 +560,32 @@ static int readheaders(int sock,
         * 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.
+        * get N copies.  This is bad when N > 1.
         *
         * 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. 
+        * a given Message-ID.  The accept_count test ensures that
+        * multiple pieces of email with the same Message-ID, each
+        * with a *single* addressee (the N == 1 case), won't be 
+        * suppressed.
+        *
+        * Note: This implementation only catches runs of successive
+        * messages with the same ID, but that should be good
+        * enough. A more general implementation would have to store
+        * ever-growing lists of seen message-IDs; in a long-running
+        * daemon this would turn into a memory leak even if the 
+        * implementation were perfect.
         * 
-        * The accept_count test ensures that multiple pieces of identical 
-        * email, each with a *single* addressee, won't be suppressed.
+        * Don't mess with this code casually.  It would be way too easy
+        * to break it in a way that blackholed mail.  Better to pass
+        * the occasional duplicate than to do that...
         */
-       if (MULTIDROP(ctl) && accept_count > 1 && !strncasecmp(line, "Message-ID:", 11))
+       if (MULTIDROP(ctl) && !strncasecmp(line, "Message-ID:", 11))
        {
            if (ctl->lastid && !strcasecmp(ctl->lastid, line))
-               return(PS_REFUSED);
+           {
+               if (accept_count > 1)
+                   return(PS_REFUSED);
+           }
            else
            {
                if (ctl->lastid)
@@ -620,6 +647,20 @@ static int readheaders(int sock,
            continue;
        }
 
+       /*
+        * We remove all Delivered-To: headers.
+        * 
+        * This is to avoid false mail loops messages when delivering
+        * local messages to and from a Postfix/qmail mailserver. 
+        * 
+        * Should be controlled by an option
+        */
+       if (ctl->dropdelivered && !strncasecmp(line, "Delivered-To:", 13)) {
+      if (delivered_to) free(line);
+      else delivered_to = line;
+         continue;
+       }
+
        /*
         * If we see a Status line, it may have been inserted by an MUA
         * on the mail host, or it may have been inserted by the server
@@ -724,14 +765,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);
@@ -739,6 +781,7 @@ static int readheaders(int sock,
                }
            }
        }
+#endif /* __UNUSED__ */
 
        else if (!MULTIDROP(ctl))
            continue;
@@ -882,6 +925,12 @@ static int readheaders(int sock,
 #endif /* SDPS_ENABLE */ 
        if (env_offs > -1)          /* We have the actual envelope addressee */
            find_server_names(msgblk.headers + env_offs, ctl, &msgblk.recipients);
+       else if (delivered_to && ctl->server.envelope != STRING_DISABLED &&
+      ctl->server.envelope && !strcasecmp(ctl->server.envelope, "Delivered-To"))
+   {
+           find_server_names(delivered_to, ctl, &msgblk.recipients);
+       free(delivered_to);
+   }
        else if (received_for)
            /*
             * We have the Received for addressee.  
@@ -980,7 +1029,16 @@ static int readheaders(int sock,
     if (!run.invisible && n != -1)
     {
        /* utter any per-message Received information we need here */
-       sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
+        if (ctl->server.trueaddr) {
+           sprintf(buf, "Received: from %s [%u.%u.%u.%u]\r\n", 
+                   ctl->server.truename,
+                   (unsigned char)ctl->server.trueaddr[0],
+                   (unsigned char)ctl->server.trueaddr[1],
+                   (unsigned char)ctl->server.trueaddr[2],
+                   (unsigned char)ctl->server.trueaddr[3]);
+       } else {
+         sprintf(buf, "Received: from %s\r\n", ctl->server.truename);
+       }
        n = stuffline(ctl, buf);
        if (n != -1)
        {
@@ -1044,7 +1102,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 && !isafile(2))
        fputs("#", stderr);
 
     /* write error notifications */
@@ -1110,7 +1168,7 @@ static int readheaders(int sock,
     *cp++ = '\0';
     stuffline(ctl, buf);
 
-    free(msgblk.headers);
+/*    free(msgblk.headers); */
     free_str_list(&msgblk.recipients);
     return(headers_ok ? PS_SUCCESS : PS_TRUNCATED);
 }
@@ -1154,7 +1212,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 && !isafile(1))
                {
                    fputc('.', stdout);
                    fflush(stdout);
@@ -1212,8 +1270,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 && !isafile(1))
+           {
+               fputc('*', stdout);
+               fflush(stdout);
+           }
        }
     }
 
@@ -1376,7 +1437,6 @@ static void send_size_warnings(struct query *ctl)
     int msg_to_send = FALSE;
     struct idlist *head=NULL, *current=NULL;
     int max_warning_poll_count;
-#define OVERHD "Subject: Fetchmail oversized-messages warning.\r\n\r\nThe following oversized messages remain on the mail server %s:"
 
     head = ctl->skipped;
     if (!head)
@@ -1396,7 +1456,11 @@ static void send_size_warnings(struct query *ctl)
      */
     if (open_warning_by_mail(ctl, (struct msgblk *)NULL))
        return;
-    stuff_warning(ctl, OVERHD, ctl->server.pollname);
+    stuff_warning(ctl,
+          _("Subject: Fetchmail oversized-messages warning.\r\n"
+            "\r\n"
+            "The following oversized messages remain on the mail server %s:"),
+                 ctl->server.pollname);
  
     if (run.poll_interval == 0)
        max_warning_poll_count = 0;
@@ -1411,7 +1475,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++;
@@ -1422,7 +1486,6 @@ static void send_size_warnings(struct query *ctl)
     }
 
     close_warning_by_mail(ctl, (struct msgblk *)NULL);
-#undef OVERHD
 }
 
 static int do_session(ctl, proto, maxfetch)
@@ -1477,9 +1540,11 @@ const int maxfetch;              /* maximum number of messages to fetch */
 
        if (js == THROW_SIGPIPE)
        {
+           signal(SIGPIPE, SIG_IGN);
            report(stdout,
-                  _("SIGPIPE thrown from an MDA or a stream socket error"));
+                  _("SIGPIPE thrown from an MDA or a stream socket error\n"));
            ok = PS_SOCKET;
+           goto cleanUp;
        }
        else if (js == THROW_TIMEOUT)
        {
@@ -1498,7 +1563,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                       ctl->mda ? "MDA" : "SMTP");
            else if (phase == LISTENER_WAIT)
                report(stdout,
-                      _("timeout after %d seconds waiting for listener to respond.\n"));
+                      _("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
            else
                report(stdout, 
                       _("timeout after %d seconds.\n"), ctl->server.timeout);
@@ -1506,6 +1571,8 @@ const int maxfetch;               /* maximum number of messages to fetch */
            /*
             * 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))
@@ -1533,13 +1600,13 @@ const int maxfetch;             /* maximum number of messages to fetch */
        /* try to clean up all streams */
        release_sink(ctl);
        if (ctl->smtp_socket != -1)
-           close(ctl->smtp_socket);
+           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_ENABLE
        int fetches, dispatches, oldphase;
@@ -1575,12 +1642,13 @@ const int maxfetch;             /* maximum number of messages to fetch */
            (void)sleep(1);
 #if INET6_ENABLE
        if ((mailserver_socket = SockOpen(realhost, 
-                            ctl->server.service ? ctl->server.service : protocol->service,
+                            ctl->server.service ? ctl->server.service : ( ctl->use_ssl ? protocol->sslservice : protocol->service ),
                             ctl->server.netsec, ctl->server.plugin)) == -1)
 #else /* INET6_ENABLE */
        if ((mailserver_socket = SockOpen(realhost, port, NULL, ctl->server.plugin)) == -1)
 #endif /* INET6_ENABLE */
        {
+           char        errbuf[BUFSIZ];
 #if !INET6_ENABLE
            int err_no = errno;
 #ifdef HAVE_RES_SEARCH
@@ -1592,30 +1660,52 @@ const int maxfetch;             /* maximum number of messages to fetch */
             * 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."));
+#ifndef __BEOS__
+                   else if (h_errno == NO_ADDRESS)
+                       strcpy(errbuf, _("name is valid but has no IP address."));
+#endif
+                   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:
+                   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)
+               {
+                   stuff_warning(ctl,
+                        _("Subject: Fetchmail unreachable-server warning.\r\n"
+                          "\r\n"
+                          "Fetchmail could not reach the mail server %s:")
+                                 ctl->server.pollname);
+                   stuff_warning(ctl, errbuf, ctl->server.pollname);
+                   close_warning_by_mail(ctl, (struct msgblk *)NULL);
+               }
+#endif
+           }
 #endif /* INET6_ENABLE */
            ok = PS_SOCKET;
            set_timeout(0);
@@ -1631,7 +1721,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                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.");
+           report(stderr, _("SSL connection failed.\n"));
            goto closeUp;
        }
 #endif
@@ -1664,6 +1754,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
            goto cleanUp;
 
        /* try to get authorized to fetch mail */
+       stage = STAGE_GETAUTH;
        if (protocol->getauth)
        {
            if (protocol->password_canonify)
@@ -1728,6 +1819,9 @@ const int maxfetch;               /* maximum number of messages to fetch */
                dispatches = 0;
                ++pass;
 
+               /* reset timeout, in case we did an IDLE */
+               mytimeout = ctl->server.timeout;
+
                if (outlevel >= O_DEBUG)
                {
                    if (idp->id)
@@ -1737,6 +1831,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                }
 
                /* compute # of messages and number of new messages waiting */
+               stage = STAGE_GETRANGE;
                ok = (protocol->getrange)(mailserver_socket, ctl, idp->id, &count, &new, &bytes);
                if (ok != 0)
                    goto cleanUp;
@@ -1785,7 +1880,12 @@ const int maxfetch;              /* maximum number of messages to fetch */
                    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)
                {    
@@ -1835,6 +1935,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                        for (i = 0; i < count; i++)
                            msgsizes[i] = -1;
 
+                       stage = STAGE_GETSIZES;
                        ok = (proto->getsizes)(mailserver_socket, count, msgsizes);
                        if (ok != 0)
                            goto cleanUp;
@@ -1848,6 +1949,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                    }
 
                    /* read, forward, and delete messages */
+                   stage = STAGE_FETCH;
                    for (num = 1; num <= count; num++)
                    {
                        flag toolarge = NUM_NONZERO(ctl->limit)
@@ -1887,7 +1989,9 @@ const int maxfetch;               /* maximum number of messages to fetch */
                        {
                            if (outlevel > O_SILENT)
                            {
-                               report_build(stdout, _("skipping message %d"), num);
+                               report_build(stdout, 
+                                    _("skipping message %d (%d octets)"),
+                                    num, msgsizes[num-1]);
                                if (toolarge && !check_only) 
                                {
                                    char size[32];
@@ -1994,7 +2098,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                             */
                            if (protocol->fetch_body && !suppress_readbody) 
                            {
-                               if (outlevel >= O_VERBOSE)
+                               if (outlevel >= O_VERBOSE && !isafile(1))
                                {
                                    fputc('\n', stdout);
                                    fflush(stdout);
@@ -2048,7 +2152,7 @@ const int maxfetch;               /* maximum number of messages to fetch */
                                /* tell server we got it OK and resynchronize */
                                if (protocol->trail)
                                {
-                                   if (outlevel >= O_VERBOSE)
+                                   if (outlevel >= O_VERBOSE && !isafile(1))
                                    {
                                        fputc('\n', stdout);
                                        fflush(stdout);
@@ -2120,7 +2224,8 @@ const int maxfetch;               /* maximum number of messages to fetch */
                            struct idlist       *sdp;
 
                            for (sdp = ctl->newsaved; sdp; sdp = sdp->next)
-                               if (sdp->val.status.num == num)
+                               if ((sdp->val.status.num == num)
+                                               && (!toolarge || oldmsg))
                                    sdp->val.status.mark = UID_SEEN;
                        }
 
@@ -2166,14 +2271,14 @@ const int maxfetch;             /* maximum number of messages to fetch */
                }
            } 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);
        }
 
-   no_error:
+    /* no_error: */
        /* ordinary termination with no errors -- officially log out */
        ok = (protocol->logout_cmd)(mailserver_socket, ctl);
        /*
@@ -2188,7 +2293,10 @@ const int maxfetch;              /* maximum number of messages to fetch */
     cleanUp:
        /* we only get here on error */
        if (ok != 0 && ok != PS_SOCKET)
+       {
+           stage = STAGE_LOGOUT;
            (protocol->logout_cmd)(mailserver_socket, ctl);
+       }
        SockClose(mailserver_socket);
     }