]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Undocumented and untested hack: setting FETCHMAIL_POP3_FORCE_RETR in the
[~andy/fetchmail] / pop3.c
1 /*
2  * pop3.c -- POP3 protocol methods
3  *
4  * Copyright 1998 by Eric S. Raymond.
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #ifdef POP3_ENABLE
10 #include  <stdio.h>
11 #include  <string.h>
12 #include  <ctype.h>
13 #if defined(HAVE_UNISTD_H)
14 #include <unistd.h>
15 #endif
16 #if defined(STDC_HEADERS)
17 #include  <stdlib.h>
18 #endif
19 #include  <errno.h>
20
21 #include  "fetchmail.h"
22 #include  "socket.h"
23 #include  "i18n.h"
24
25 #ifdef OPIE_ENABLE
26 #ifdef __cplusplus
27 extern "C" {
28 #endif
29 #include <opie.h>
30 #ifdef __cplusplus
31 }
32 #endif
33 #endif /* OPIE_ENABLE */
34
35 /* global variables: please reinitialize them explicitly for proper
36  * working in daemon mode */
37
38 /* TODO: session variables to be initialized before server greeting */
39 #ifdef OPIE_ENABLE
40 static char lastok[POPBUFSIZE+1];
41 #endif /* OPIE_ENABLE */
42
43 /* session variables initialized in capa_probe() or pop3_getauth() */
44 flag done_capa = FALSE;
45 #if defined(GSSAPI)
46 flag has_gssapi = FALSE;
47 #endif /* defined(GSSAPI) */
48 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
49 flag has_kerberos = FALSE;
50 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
51 static flag has_cram = FALSE;
52 #ifdef OPIE_ENABLE
53 flag has_otp = FALSE;
54 #endif /* OPIE_ENABLE */
55 #ifdef SSL_ENABLE
56 static flag has_stls = FALSE;
57 #endif /* SSL_ENABLE */
58
59 /* mailbox variables initialized in pop3_getrange() */
60 static int last;
61
62 /* mail variables initialized in pop3_fetch() */
63 #ifdef SDPS_ENABLE
64 char *sdps_envfrom;
65 char *sdps_envto;
66 #endif /* SDPS_ENABLE */
67
68 #ifdef NTLM_ENABLE
69 #include "ntlm.h"
70
71 /*
72  * NTLM support by Grant Edwards.
73  *
74  * Handle MS-Exchange NTLM authentication method.  This is the same
75  * as the NTLM auth used by Samba for SMB related services. We just
76  * encode the packets in base64 instead of sending them out via a
77  * network interface.
78  * 
79  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
80  */
81
82 static int do_pop3_ntlm(int sock, struct query *ctl,
83         int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
84 {
85     tSmbNtlmAuthRequest request;
86     tSmbNtlmAuthChallenge challenge;
87     tSmbNtlmAuthResponse response;
88
89     char msgbuf[2048];
90     int result,len;
91   
92     gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
93
94     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
95         return result;
96   
97     if (msgbuf[0] != '+')
98         return PS_AUTHFAIL;
99   
100     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
101
102     if (outlevel >= O_DEBUG)
103         dumpSmbNtlmAuthRequest(stdout, &request);
104
105     memset(msgbuf,0,sizeof msgbuf);
106     to64frombits (msgbuf, &request, SmbLength(&request));
107   
108     if (outlevel >= O_MONITOR)
109         report(stdout, "POP3> %s\n", msgbuf);
110   
111     strcat(msgbuf,"\r\n");
112     SockWrite (sock, msgbuf, strlen (msgbuf));
113
114     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
115         return result;
116   
117     len = from64tobits (&challenge, msgbuf, sizeof(msgbuf));
118     
119     if (outlevel >= O_DEBUG)
120         dumpSmbNtlmAuthChallenge(stdout, &challenge);
121     
122     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
123   
124     if (outlevel >= O_DEBUG)
125         dumpSmbNtlmAuthResponse(stdout, &response);
126   
127     memset(msgbuf,0,sizeof msgbuf);
128     to64frombits (msgbuf, &response, SmbLength(&response));
129
130     if (outlevel >= O_MONITOR)
131         report(stdout, "POP3> %s\n", msgbuf);
132       
133     strcat(msgbuf,"\r\n");
134     SockWrite (sock, msgbuf, strlen (msgbuf));
135   
136     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
137         return result;
138   
139     if (strstr (msgbuf, "OK"))
140         return PS_SUCCESS;
141     else
142         return PS_AUTHFAIL;
143 }
144 #endif /* NTLM */
145
146
147 #define DOTLINE(s)      (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
148
149 static int pop3_ok (int sock, char *argbuf)
150 /* parse command response */
151 {
152     int ok;
153     char buf [POPBUFSIZE+1];
154     char *bufp;
155
156     if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
157     {   bufp = buf;
158         if (*bufp == '+' || *bufp == '-')
159             bufp++;
160         else
161             return(PS_PROTOCOL);
162
163         while (isalpha((unsigned char)*bufp))
164             bufp++;
165
166         if (*bufp)
167           *(bufp++) = '\0';
168
169         if (strcmp(buf,"+OK") == 0)
170         {
171 #ifdef OPIE_ENABLE
172             strcpy(lastok, bufp);
173 #endif /* OPIE_ENABLE */
174             ok = 0;
175         }
176         else if (strncmp(buf,"-ERR", 4) == 0)
177         {
178             if (stage == STAGE_FETCH)
179                 ok = PS_TRANSIENT;
180             else if (stage > STAGE_GETAUTH)
181                 ok = PS_PROTOCOL;
182             /*
183              * We're checking for "lock busy", "unable to lock", 
184              * "already locked", "wait a few minutes" etc. here. 
185              * This indicates that we have to wait for the server to
186              * unwedge itself before we can poll again.
187              *
188              * PS_LOCKBUSY check empirically verified with two recent
189              * versions of the Berkeley popper; QPOP (version 2.2)  and
190              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
191              * These are caught by the case-indifferent "lock" check.
192              * The "wait" catches "mail storage services unavailable,
193              * wait a few minutes and try again" on the InterMail server.
194              *
195              * If these aren't picked up on correctly, fetchmail will 
196              * think there is an authentication failure and wedge the
197              * connection in order to prevent futile polls.
198              *
199              * Gad, what a kluge.
200              */
201             else if (strstr(bufp,"lock")
202                      || strstr(bufp,"Lock")
203                      || strstr(bufp,"LOCK")
204                      || strstr(bufp,"wait")
205                      /* these are blessed by RFC 2449 */
206                      || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
207                 ok = PS_LOCKBUSY;
208             else if ((strstr(bufp,"Service")
209                      || strstr(bufp,"service"))
210                          && (strstr(bufp,"unavailable")))
211                 ok = PS_SERVBUSY;
212             else
213                 ok = PS_AUTHFAIL;
214             /*
215              * We always want to pass the user lock-busy messages, because
216              * they're red flags.  Other stuff (like AUTH failures on non-
217              * RFC1734 servers) only if we're debugging.
218              */
219             if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
220               report(stderr, "%s\n", bufp);
221         }
222         else
223             ok = PS_PROTOCOL;
224
225 #if POPBUFSIZE > MSGBUFSIZE
226 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
227 #endif
228         if (argbuf != NULL)
229             strcpy(argbuf,bufp);
230     }
231
232     return(ok);
233 }
234
235
236
237 static int capa_probe(int sock)
238 /* probe the capabilities of the remote server */
239 {
240     int ok;
241
242     if (done_capa) {
243         return PS_SUCCESS;
244     }
245 #if defined(GSSAPI)
246     has_gssapi = FALSE;
247 #endif /* defined(GSSAPI) */
248 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
249     has_kerberos = FALSE;
250 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
251     has_cram = FALSE;
252 #ifdef OPIE_ENABLE
253     has_otp = FALSE;
254 #endif /* OPIE_ENABLE */
255
256     ok = gen_transact(sock, "CAPA");
257     if (ok == PS_SUCCESS)
258     {
259         char buffer[64];
260
261         /* determine what authentication methods we have available */
262         while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
263         {
264             if (DOTLINE(buffer))
265                 break;
266 #ifdef SSL_ENABLE
267             if (strstr(buffer, "STLS"))
268                 has_stls = TRUE;
269 #endif /* SSL_ENABLE */
270 #if defined(GSSAPI)
271             if (strstr(buffer, "GSSAPI"))
272                 has_gssapi = TRUE;
273 #endif /* defined(GSSAPI) */
274 #if defined(KERBEROS_V4)
275             if (strstr(buffer, "KERBEROS_V4"))
276                 has_kerberos = TRUE;
277 #endif /* defined(KERBEROS_V4)  */
278 #ifdef OPIE_ENABLE
279             if (strstr(buffer, "X-OTP"))
280                 has_otp = TRUE;
281 #endif /* OPIE_ENABLE */
282             if (strstr(buffer, "CRAM-MD5"))
283                 has_cram = TRUE;
284         }
285     }
286     done_capa = TRUE;
287     return(ok);
288 }
289
290 static void set_peek_capable(struct query *ctl)
291 {
292     /* we're peek-capable means that the use of TOP is enabled,
293      * see pop3_fetch for details - short story, we can use TOP if
294      * we have a means of reliably tracking which mail we need to
295      * refetch should the connection abort in the middle.
296      * fetchall forces RETR, as does keep without UIDL */
297     peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
298 }
299
300 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
301 /* apply for connection authorization */
302 {
303     int ok;
304     char *start,*end;
305     char *msg;
306 #ifdef OPIE_ENABLE
307     char *challenge;
308 #endif /* OPIE_ENABLE */
309 #ifdef SSL_ENABLE
310     char *realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
311     flag connection_may_have_tls_errors = FALSE;
312     flag got_tls = FALSE;
313 #endif /* SSL_ENABLE */
314
315     done_capa = FALSE;
316 #if defined(GSSAPI)
317     has_gssapi = FALSE;
318 #endif /* defined(GSSAPI) */
319 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
320     has_kerberos = FALSE;
321 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
322     has_cram = FALSE;
323 #ifdef OPIE_ENABLE
324     has_otp = FALSE;
325 #endif /* OPIE_ENABLE */
326 #ifdef SSL_ENABLE
327     has_stls = FALSE;
328 #endif /* SSL_ENABLE */
329
330     /* Set this up before authentication quits early. */
331     set_peek_capable(ctl);
332
333     /* Hack: allow user to force RETR. */
334     if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
335         peek_capable = 0;
336     }
337
338     /*
339      * The "Maillennium POP3/PROXY server" deliberately truncates
340      * TOP replies after c. 64 or 80 kByte (we have varying reports), so
341      * disable TOP. Comcast once spewed marketing babble to the extent
342      * of protecting Outlook -- pretty overzealous to break a protocol
343      * for that that Microsoft could have read, too. Comcast aren't
344      * alone in using this software though.
345      * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
346      * (Thanks to Ed Wilts for reminding me of that.)
347      *
348      * The warning is printed once per server, until fetchmail exits.
349      * It will be suppressed when --fetchall or other circumstances make
350      * us use RETR anyhow.
351      *
352      * Matthias Andree
353      */
354     if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
355         if ((ctl->server.workarounds & WKA_TOP) == 0) {
356             report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
357             ctl->server.workarounds |= WKA_TOP;
358         }
359         peek_capable = 0;
360     }
361     if (ctl->server.authenticate == A_SSH) {
362         return PS_SUCCESS;
363     }
364
365 #ifdef SDPS_ENABLE
366     /*
367      * This needs to catch both demon.co.uk and demon.net.
368      * If we see either, and we're in multidrop mode, try to use
369      * the SDPS *ENV extension.
370      */
371     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
372         ctl->server.sdps = TRUE;
373 #endif /* SDPS_ENABLE */
374
375 #ifdef NTLM_ENABLE
376     /* MSN servers require the use of NTLM (MSN) authentication */
377     if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
378             ctl->server.authenticate == A_MSN)
379         return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
380     if (ctl->server.authenticate == A_NTLM)
381         return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
382 #else
383     if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
384     {
385         report(stderr,
386            GT_("Required NTLM capability not compiled into fetchmail\n"));
387     }
388 #endif
389
390     switch (ctl->server.protocol) {
391     case P_POP3:
392 #ifdef RPA_ENABLE
393         /* XXX FIXME: AUTH probing (RFC1734) should become global */
394         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
395         if (strstr(ctl->remotename, "@compuserve.com"))
396         {
397             /* AUTH command should return a list of available mechanisms */
398             if (gen_transact(sock, "AUTH") == 0)
399             {
400                 char buffer[10];
401                 flag has_rpa = FALSE;
402
403                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
404                 {
405                     if (DOTLINE(buffer))
406                         break;
407                     if (strncasecmp(buffer, "rpa", 3) == 0)
408                         has_rpa = TRUE;
409                 }
410                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
411                                               ctl->password, sock))
412                     return(PS_SUCCESS);
413             }
414
415             return(PS_AUTHFAIL);
416         }
417 #endif /* RPA_ENABLE */
418
419         /*
420          * CAPA command may return a list including available
421          * authentication mechanisms and STLS capability.
422          *
423          * If it doesn't, no harm done, we just fall back to a plain
424          * login -- if the user allows it.
425          *
426          * Note that this code latches the server's authentication type,
427          * so that in daemon mode the CAPA check only needs to be done
428          * once at start of run.
429          *
430          * If CAPA fails, then force the authentication method to
431          * PASSWORD, switch off opportunistic and repoll immediately.
432          * If TLS is mandatory, fail up front.
433          */
434         if ((ctl->server.authenticate == A_ANY) ||
435                 (ctl->server.authenticate == A_GSSAPI) ||
436                 (ctl->server.authenticate == A_KERBEROS_V4) ||
437                 (ctl->server.authenticate == A_KERBEROS_V5) ||
438                 (ctl->server.authenticate == A_OTP) ||
439                 (ctl->server.authenticate == A_CRAM_MD5) ||
440                 maybe_tls(ctl))
441         {
442             if ((ok = capa_probe(sock)) != PS_SUCCESS)
443                 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
444                 if (ok == PS_AUTHFAIL ||
445                     /* Some servers directly close the socket. However, if we
446                      * have already authenticated before, then a previous CAPA
447                      * must have succeeded. In that case, treat this as a
448                      * genuine socket error and do not change the auth method.
449                      */
450                     (ok == PS_SOCKET && !ctl->wehaveauthed))
451                 {
452 #ifdef SSL_ENABLE
453                     if (must_tls(ctl)) {
454                         /* fail with mandatory STLS without repoll */
455                         report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
456                         report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
457                         return ok;
458                     } else if (maybe_tls(ctl)) {
459                         /* defeat opportunistic STLS */
460                         xfree(ctl->sslproto);
461                         ctl->sslproto = xstrdup("");
462                     }
463 #endif
464                     /* If strong authentication was opportunistic, retry without, else fail. */
465                     switch (ctl->server.authenticate) {
466                         case A_ANY:
467                             ctl->server.authenticate = A_PASSWORD;
468                             /* FALLTHROUGH */
469                         case A_PASSWORD: /* this should only happen with TLS enabled */
470                             return PS_REPOLL;
471                         default:
472                             return PS_AUTHFAIL;
473                     }
474                 }
475         }
476
477 #ifdef SSL_ENABLE
478         if (maybe_tls(ctl)) {
479            if (has_stls)
480            {
481                /* Use "tls1" rather than ctl->sslproto because tls1 is the only
482                 * protocol that will work with STARTTLS.  Don't need to worry
483                 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
484                 * (see below). */
485                if (gen_transact(sock, "STLS") == PS_SUCCESS
486                        && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
487                            ctl->sslcertpath, ctl->sslfingerprint, realhost,
488                            ctl->server.pollname, &ctl->remotename) != -1)
489                {
490                    /*
491                     * RFC 2595 says this:
492                     *
493                     * "Once TLS has been started, the client MUST discard cached
494                     * information about server capabilities and SHOULD re-issue the
495                     * CAPABILITY command.  This is necessary to protect against
496                     * man-in-the-middle attacks which alter the capabilities list prior
497                     * to STARTTLS.  The server MAY advertise different capabilities
498                     * after STARTTLS."
499                     *
500                     * Now that we're confident in our TLS connection we can
501                     * guarantee a secure capability re-probe.
502                     */
503                    got_tls = TRUE;
504                    done_capa = FALSE;
505                    ok = capa_probe(sock);
506                    if (ok != PS_SUCCESS) {
507                        return ok;
508                    }
509                    if (outlevel >= O_VERBOSE)
510                    {
511                        report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), realhost);
512                    }
513                }
514            }
515
516            if (!got_tls) {
517                if (must_tls(ctl)) {
518                    /* Config required TLS but we couldn't guarantee it, so we must
519                     * stop. */
520                    report(stderr, GT_("%s: upgrade to TLS failed.\n"), realhost);
521                    return PS_SOCKET;
522                } else {
523                    /* We don't know whether the connection is usable, and there's
524                     * no command we can reasonably issue to test it (NOOP isn't
525                     * allowed til post-authentication), so leave it in an unknown
526                     * state, mark it as such, and check more carefully if things
527                     * go wrong when we try to authenticate. */
528                    connection_may_have_tls_errors = TRUE;
529                    if (outlevel >= O_VERBOSE)
530                    {
531                        report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), realhost);
532                    }
533                }
534            }
535         } /* maybe_tls() */
536 #endif /* SSL_ENABLE */
537
538         /*
539          * OK, we have an authentication type now.
540          */
541 #if defined(KERBEROS_V4)
542         /* 
543          * Servers doing KPOP have to go through a dummy login sequence
544          * rather than doing SASL.
545          */
546         if (has_kerberos &&
547             ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
548             && (ctl->server.authenticate == A_KERBEROS_V4
549              || ctl->server.authenticate == A_KERBEROS_V5
550              || ctl->server.authenticate == A_ANY))
551         {
552             ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
553             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
554                 break;
555         }
556 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
557
558 #if defined(GSSAPI)
559         if (has_gssapi &&
560             (ctl->server.authenticate == A_GSSAPI ||
561              ctl->server.authenticate == A_ANY))
562         {
563             ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
564             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
565                 break;
566         }
567 #endif /* defined(GSSAPI) */
568
569 #ifdef OPIE_ENABLE
570         if (has_otp &&
571             (ctl->server.authenticate == A_OTP ||
572              ctl->server.authenticate == A_ANY))
573         {
574             ok = do_otp(sock, "AUTH", ctl);
575             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
576                 break;
577         }
578 #endif /* OPIE_ENABLE */
579
580         if (ctl->server.authenticate == A_CRAM_MD5 || 
581             (has_cram && ctl->server.authenticate == A_ANY))
582         {
583             ok = do_cram_md5(sock, "AUTH", ctl, NULL);
584             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
585                 break;
586         }
587
588         /* ordinary validation, no one-time password or RPA */ 
589         if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
590             break;
591
592 #ifdef OPIE_ENABLE
593         /* see RFC1938: A One-Time Password System */
594         if ((challenge = strstr(lastok, "otp-"))) {
595           char response[OPIE_RESPONSE_MAX+1];
596           int i;
597           char *n = xstrdup("");
598
599           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
600           free(n);
601           if ((i == -2) && !run.poll_interval) {
602             char secret[OPIE_SECRET_MAX+1];
603             fprintf(stderr, GT_("Secret pass phrase: "));
604             if (opiereadpass(secret, sizeof(secret), 0))
605               i = opiegenerator(challenge,  secret, response);
606             memset(secret, 0, sizeof(secret));
607           };
608
609           if (i) {
610             ok = PS_ERROR;
611             break;
612           };
613
614           ok = gen_transact(sock, "PASS %s", response);
615           break;
616         }
617 #endif /* OPIE_ENABLE */
618
619         /* KPOP uses out-of-band authentication and does not check what
620          * we send here, so send some random fixed string, to avoid
621          * users switching *to* KPOP accidentally revealing their
622          * password */
623         if ((ctl->server.authenticate == A_ANY
624                     || ctl->server.authenticate == A_KERBEROS_V4
625                     || ctl->server.authenticate == A_KERBEROS_V5)
626                 && (ctl->server.service != NULL
627                     && strcmp(ctl->server.service, KPOP_PORT) == 0))
628         {
629             ok = gen_transact(sock, "PASS krb_ticket");
630             break;
631         }
632
633         /* check if we are actually allowed to send the password */
634         if (ctl->server.authenticate == A_ANY
635                 || ctl->server.authenticate == A_PASSWORD) {
636             strlcpy(shroud, ctl->password, sizeof(shroud));
637             ok = gen_transact(sock, "PASS %s", ctl->password);
638         } else {
639             report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
640             ok = PS_AUTHFAIL;
641         }
642         memset(shroud, 0x55, sizeof(shroud));
643         shroud[0] = '\0';
644         break;
645
646     case P_APOP:
647         /* build MD5 digest from greeting timestamp + password */
648         /* find start of timestamp */
649         for (start = greeting;  *start != 0 && *start != '<';  start++)
650             continue;
651         if (*start == 0) {
652             report(stderr,
653                    GT_("Required APOP timestamp not found in greeting\n"));
654             return(PS_AUTHFAIL);
655         }
656
657         /* find end of timestamp */
658         for (end = start;  *end != 0  && *end != '>';  end++)
659             continue;
660         if (*end == 0 || end == start + 1) {
661             report(stderr, 
662                    GT_("Timestamp syntax error in greeting\n"));
663             return(PS_AUTHFAIL);
664         }
665         else
666             *++end = '\0';
667
668         /* SECURITY: 2007-03-17
669          * Strictly validating the presented challenge for RFC-822
670          * conformity (it must be a msg-id in terms of that standard) is
671          * supposed to make attacks against the MD5 implementation
672          * harder[1]
673          *
674          * [1] "Security vulnerability in APOP authentication",
675          *     Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
676         if (!rfc822_valid_msgid((unsigned char *)start)) {
677             report(stderr,
678                     GT_("Invalid APOP timestamp.\n"));
679             return PS_AUTHFAIL;
680         }
681
682         /* copy timestamp and password into digestion buffer */
683         msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
684         strcpy(msg,start);
685         strcat(msg,ctl->password);
686         strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
687         free(msg);
688
689         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
690         break;
691
692     case P_RPOP:
693         if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
694             strlcpy(shroud, ctl->password, sizeof(shroud));
695             ok = gen_transact(sock, "RPOP %s", ctl->password);
696             memset(shroud, 0x55, sizeof(shroud));
697             shroud[0] = '\0';
698         }
699         break;
700
701     default:
702         report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
703         ok = PS_ERROR;
704     }
705
706 #ifdef SSL_ENABLE
707     /* this is for servers which claim to support TLS, but actually
708      * don't! */
709     if (connection_may_have_tls_errors
710                     && (ok == PS_SOCKET || ok == PS_PROTOCOL))
711     {
712         xfree(ctl->sslproto);
713         ctl->sslproto = xstrdup("");
714         /* repoll immediately without TLS */
715         ok = PS_REPOLL;
716     }
717 #endif
718
719     if (ok != 0)
720     {
721         /* maybe we detected a lock-busy condition? */
722         if (ok == PS_LOCKBUSY)
723             report(stderr, GT_("lock busy!  Is another session active?\n")); 
724
725         return(ok);
726     }
727
728 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
729  * accepted by Matthias Andree.
730  *
731  * Rationale: the server must have locked the spool before returning +OK;
732  * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
733 #ifdef WANT_BOGUS
734     /*
735      * Empirical experience shows some server/OS combinations
736      * may need a brief pause even after any lockfiles on the
737      * server are released, to give the server time to finish
738      * copying back very large mailfolders from the temp-file...
739      * this is only ever an issue with extremely large mailboxes.
740      */
741     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
742 #endif
743
744     /* we're approved */
745     return(PS_SUCCESS);
746 }
747
748 /* cut off C string at first POSIX space */
749 static void trim(char *s) {
750     s += strcspn(s, POSIX_space);
751     s[0] = '\0';
752 }
753
754 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
755  * broken messages) do not have Message-ID headers, and messages without
756  * those appear to break this code and cause fetchmail (at least version
757  * 6.2.3) to not delete such messages properly after retrieval.
758  * See Sourceforge Bug #780933.
759  *
760  * The other problem is that the TOP command itself is optional, too... */
761 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
762 {
763     int ok;
764     int got_it;
765     char buf [POPBUFSIZE+1];
766     snprintf(buf, sizeof(buf), "TOP %d 1", num);
767     if ((ok = gen_transact(sock, buf )) != 0)
768        return ok;
769     got_it = 0;
770     while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) 
771     {
772         if (DOTLINE(buf))
773             break;
774         if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
775             char *p = buf + 11;
776             got_it = 1;
777             p += strspn(p, POSIX_space);
778             strlcpy(id, p, idsize);
779             trim(id);
780         }
781     }
782     /* XXX FIXME: do not return success here if no Message-ID header was
783      * found. */
784     return 0;
785 }
786
787 /** Parse the UID response (leading +OK must have been
788  * stripped off) in buf, store the number in gotnum, and store the ID
789  * into the caller-provided buffer "id" of size "idsize".
790  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
791 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
792 {
793     const char *i;
794     char *j;
795
796     /* skip leading blanks ourselves */
797     i = buf;
798     i += strspn(i, POSIX_space);
799     errno = 0;
800     *gotnum = strtoul(i, &j, 10);
801     if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
802         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
803         return PS_PROTOCOL;
804     }
805     j += strspn(j, POSIX_space);
806     strlcpy(id, j, idsize);
807     trim(id);
808     return PS_SUCCESS;
809 }
810
811 /** request UIDL for single message \a num and stuff the result into the
812  * buffer \a id which can hold \a idsize bytes */
813 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
814 {
815     int ok;
816     char buf [POPBUFSIZE+1];
817     unsigned long gotnum;
818
819     gen_send(sock, "UIDL %d", num);
820     if ((ok = pop3_ok(sock, buf)) != 0)
821         return(ok);
822     if ((ok = parseuid(buf, &gotnum, id, idsize)))
823         return ok;
824     if (gotnum != (unsigned long)num) {
825         report(stderr, GT_("Server responded with UID for wrong message.\n"));
826         return PS_PROTOCOL;
827     }
828     return(PS_SUCCESS);
829 }
830
831 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
832 {
833     int ok;
834     unsigned int first_nr, last_nr, try_nr;
835     char id [IDLEN+1];
836
837     first_nr = 0;
838     last_nr = count + 1;
839     while (first_nr < last_nr - 1)
840     {
841         struct idlist   *newl;
842
843         try_nr = (first_nr + last_nr) / 2;
844         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
845             return ok;
846         if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
847         {
848             flag mark = newl->val.status.mark;
849             if (mark == UID_DELETED || mark == UID_EXPUNGED)
850             {
851                 if (outlevel >= O_VERBOSE)
852                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
853                 /* just mark it as seen now! */
854                 newl->val.status.mark = mark = UID_SEEN;
855             }
856
857             /* narrow the search region! */
858             if (mark == UID_UNSEEN)
859             {
860                 if (outlevel >= O_DEBUG)
861                     report(stdout, GT_("%u is unseen\n"), try_nr);
862                 last_nr = try_nr;
863             }
864             else
865                 first_nr = try_nr;
866
867             /* save the number */
868             newl->val.status.num = try_nr;
869         }
870         else
871         {
872             if (outlevel >= O_DEBUG)
873                 report(stdout, GT_("%u is unseen\n"), try_nr);
874             last_nr = try_nr;
875
876             /* save it */
877             newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
878             newl->val.status.num = try_nr;
879         }
880     }
881     if (outlevel >= O_DEBUG && last_nr <= count)
882         report(stdout, GT_("%u is first unseen\n"), last_nr);
883
884     /* update last! */
885     *newp = count - first_nr;
886     last = first_nr;
887     return 0;
888 }
889
890 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
891 {
892     /* XXX FIXME: this code is severely broken. A Cc:d mailing list
893      * message will arrive twice with the same Message-ID, so this
894      * slowuidl code will break. Same goes for messages without
895      * Message-ID headers at all. This code would best be removed. */
896     /* This approach tries to get the message headers from the
897      * remote hosts and compares the message-id to the already known
898      * ones:
899      *  + if the first message containes a new id, all messages on
900      *    the server will be new
901      *  + if the first is known, try to estimate the last known message
902      *    on the server and check. If this works you know the total number
903      *    of messages to get.
904      *  + Otherwise run a binary search to determine the last known message
905      */
906     int ok, nolinear = 0;
907     int first_nr, list_len, try_id, try_nr, add_id;
908     int num;
909     char id [IDLEN+1];
910
911     if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
912         return ok;
913
914     if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
915         /* the first message is unknown -> all messages are new */
916         *newp = *countp;        
917         return 0;
918     }
919
920     /* check where we expect the latest known message */
921     list_len = count_list( &ctl->oldsaved );
922     try_id = list_len  - first_nr; /* -1 + 1 */
923     if( try_id > 1 ) {
924         if( try_id <= *countp ) {
925             if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
926                 return ok;
927     
928             try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
929         } else {
930             try_id = *countp+1;
931             try_nr = -1;
932         }
933         if( try_nr != list_len -1 ) {
934             /* some messages inbetween have been deleted... */
935             if( try_nr == -1 ) {
936                 nolinear = 1;
937
938                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
939                     ;
940                 for( ; add_id; add_id >>= 1 ) {
941                     if( try_nr == -1 ) {
942                         if( try_id - add_id <= 1 ) {
943                             continue;
944                         }
945                         try_id -= add_id;
946                     } else 
947                         try_id += add_id;
948                     
949                     if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
950                         return ok;
951                     try_nr = str_nr_in_list(&ctl->oldsaved, id);
952                 }
953                 if( try_nr == -1 ) {
954                     try_id--;
955                 }
956             } else {
957                 report(stderr, 
958                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
959                 return -1;
960             }
961         } 
962     }
963     /* the first try_id messages are known -> copy them to the newsaved list */
964     for( num = first_nr; num < list_len; num++ )
965     {
966         struct idlist   *newl = save_str(&ctl->newsaved, 
967                                 str_from_nr_list(&ctl->oldsaved, num),
968                                 UID_UNSEEN);
969         newl->val.status.num = num - first_nr + 1;
970     }
971
972     if( nolinear ) {
973         free_str_list(&ctl->oldsaved);
974         ctl->oldsaved = 0;
975         last = try_id;
976     }
977
978     *newp = *countp - try_id;
979     return 0;
980 }
981
982 static int pop3_getrange(int sock, 
983                          struct query *ctl,
984                          const char *folder,
985                          int *countp, int *newp, int *bytes)
986 /* get range of messages to be fetched */
987 {
988     int ok;
989     char buf [POPBUFSIZE+1];
990
991     (void)folder;
992     /* Ensure that the new list is properly empty */
993     ctl->newsaved = (struct idlist *)NULL;
994
995 #ifdef MBOX
996     /* Alain Knaff suggests this, but it's not RFC standard */
997     if (folder)
998         if ((ok = gen_transact(sock, "MBOX %s", folder)))
999             return ok;
1000 #endif /* MBOX */
1001
1002     /* get the total message count */
1003     gen_send(sock, "STAT");
1004     ok = pop3_ok(sock, buf);
1005     if (ok == 0)
1006         sscanf(buf,"%d %d", countp, bytes);
1007     else
1008         return(ok);
1009
1010     /*
1011      * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
1012      * command.  We work as hard as possible to hide this, but it makes
1013      * counting new messages intrinsically quadratic in the worst case.
1014      */
1015     last = 0;
1016     *newp = -1;
1017     /* if there are messages, and UIDL is desired, use UIDL
1018      * also use UIDL if fetchall is unset */
1019     if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
1020     {
1021         int fastuidl;
1022         char id [IDLEN+1];
1023
1024         /* should we do fast uidl this time? */
1025         fastuidl = ctl->fastuidl;
1026         if (*countp > 7 &&              /* linear search is better if there are few mails! */
1027             !ctl->fetchall &&           /* with fetchall, all uids are required */
1028             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
1029             NUM_NONZERO (fastuidl))
1030         {
1031             if (fastuidl == 1)
1032                 dofastuidl = 1;
1033             else
1034                 dofastuidl = ctl->fastuidlcount != 0;
1035         }
1036         else
1037             dofastuidl = 0;
1038
1039         if (!ctl->server.uidl) {
1040             gen_send(sock, "LAST");
1041             ok = pop3_ok(sock, buf);
1042         } else
1043             ok = 1;
1044
1045         if (ok == 0)
1046         {
1047             /* scan LAST reply */
1048             if (sscanf(buf, "%d", &last) == 0)
1049             {
1050                 report(stderr, GT_("protocol error\n"));
1051                 return(PS_ERROR);
1052             }
1053             *newp = (*countp - last);
1054         }
1055         else
1056         {
1057             /* do UIDL */
1058             if (dofastuidl)
1059                 return(pop3_fastuidl( sock, ctl, *countp, newp));
1060             /* grab the mailbox's UID list */
1061             if ((ok = gen_transact(sock, "UIDL")) != 0)
1062             {
1063                 /* don't worry, yet! do it the slow way */
1064                 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
1065                 {
1066                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
1067                     return(PS_ERROR);
1068                 }
1069             }
1070             else
1071             {
1072                 /* UIDL worked - parse reply */
1073                 unsigned long unum;
1074
1075                 *newp = 0;
1076                 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
1077                 {
1078                     if (DOTLINE(buf))
1079                         break;
1080
1081                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1082                     {
1083                         struct idlist   *old, *newl;
1084
1085                         newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
1086                         newl->val.status.num = unum;
1087
1088                         if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
1089                         {
1090                             flag mark = old->val.status.mark;
1091                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
1092                             {
1093                                 /* XXX FIXME: switch 3 occurrences from
1094                                  * (int)unum or (unsigned int)unum to
1095                                  * remove the cast and use %lu - not now
1096                                  * though, time for new release */
1097                                 if (outlevel >= O_VERBOSE)
1098                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1099                                 /* just mark it as seen now! */
1100                                 old->val.status.mark = mark = UID_SEEN;
1101                             }
1102                             newl->val.status.mark = mark;
1103                             if (mark == UID_UNSEEN)
1104                             {
1105                                 (*newp)++;
1106                                 if (outlevel >= O_DEBUG)
1107                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1108                             }
1109                         }
1110                         else
1111                         {
1112                             (*newp)++;
1113                             if (outlevel >= O_DEBUG)
1114                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1115                             /* add it to oldsaved also! In case, we do not
1116                              * swap the lists (say, due to socket error),
1117                              * the same mail will not be downloaded again.
1118                              */
1119                             old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1120                         }
1121                         /* save the number */
1122                         old->val.status.num = unum;
1123                     } else
1124                         return PS_ERROR;
1125                 } /* multi-line loop for UIDL reply */
1126             } /* UIDL parser */
1127         } /* do UIDL */
1128     }
1129
1130     return(PS_SUCCESS);
1131 }
1132
1133 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1134 /* capture the size of message #first */
1135 {
1136     int ok = 0, i, num;
1137     char buf [POPBUFSIZE+1];
1138     unsigned int size;
1139
1140     for (i = first; i <= last; i++) {
1141         gen_send(sock, "LIST %d", i);
1142         if ((ok = pop3_ok(sock, buf)) != 0)
1143             return(ok);
1144         if (sscanf(buf, "%d %u", &num, &size) == 2) {
1145             if (num == i)
1146                 sizes[i - first] = size;
1147             else
1148                 /* warn about possible attempt to induce buffer overrun
1149                  *
1150                  * we expect server reply message number and requested
1151                  * message number to match */
1152                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1153         }
1154     }
1155     return(ok);
1156 }
1157
1158 static int pop3_getsizes(int sock, int count, int *sizes)
1159 /* capture the sizes of all messages */
1160 {
1161     int ok;
1162
1163     if ((ok = gen_transact(sock, "LIST")) != 0)
1164         return(ok);
1165     else
1166     {
1167         char buf [POPBUFSIZE+1];
1168
1169         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1170         {
1171             unsigned int num, size;
1172
1173             if (DOTLINE(buf))
1174                 break;
1175             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1176                 if (num > 0 && num <= (unsigned)count)
1177                     sizes[num - 1] = size;
1178                 else
1179                     /* warn about possible attempt to induce buffer overrun */
1180                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1181             }
1182         }
1183
1184         return(ok);
1185     }
1186 }
1187
1188 static int pop3_is_old(int sock, struct query *ctl, int num)
1189 /* is the given message old? */
1190 {
1191     struct idlist *newl;
1192     if (!ctl->oldsaved)
1193         return (num <= last);
1194     else if (dofastuidl)
1195     {
1196         char id [IDLEN+1];
1197
1198         if (num <= last)
1199             return(TRUE);
1200
1201         /* in fast uidl, we manipulate the old list only! */
1202
1203         if ((newl = id_find(&ctl->oldsaved, num)))
1204         {
1205             /* we already have the id! */
1206             return(newl->val.status.mark != UID_UNSEEN);
1207         }
1208
1209         /* get the uidl first! */
1210         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1211             return(TRUE);
1212
1213         if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1214             /* we already have the id! */
1215             newl->val.status.num = num;
1216             return(newl->val.status.mark != UID_UNSEEN);
1217         }
1218
1219         /* save it */
1220         newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1221         newl->val.status.num = num;
1222         return(FALSE);
1223     }
1224     else
1225         return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1226             newl->val.status.mark != UID_UNSEEN);
1227 }
1228
1229 #ifdef UNUSED
1230 /*
1231  * We could use this to fetch headers only as we do for IMAP.  The trouble 
1232  * is that there's no way to fetch the body only.  So the following RETR 
1233  * would have to re-fetch the header.  Enough messages have longer headers
1234  * than bodies to make this a net loss.
1235  */
1236 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1237 /* request headers of nth message */
1238 {
1239     int ok;
1240     char buf[POPBUFSIZE+1];
1241
1242     gen_send(sock, "TOP %d 0", number);
1243     if ((ok = pop3_ok(sock, buf)) != 0)
1244         return(ok);
1245
1246     *lenp = -1;         /* we got sizes from the LIST response */
1247
1248     return(PS_SUCCESS);
1249 }
1250 #endif /* UNUSED */
1251
1252 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1253 /* request nth message */
1254 {
1255     int ok;
1256     char buf[POPBUFSIZE+1];
1257
1258 #ifdef SDPS_ENABLE
1259     /*
1260      * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1261      * for a description of what we're parsing here.
1262      * -- updated 2006-02-22
1263      */
1264     if (ctl->server.sdps)
1265     {
1266         int     linecount = 0;
1267
1268         sdps_envfrom = (char *)NULL;
1269         sdps_envto = (char *)NULL;
1270         gen_send(sock, "*ENV %d", number);
1271         do {
1272             if (gen_recv(sock, buf, sizeof(buf)))
1273             {
1274                 break;
1275             }
1276             linecount++;
1277             switch (linecount) {
1278             case 4:
1279                 /* No need to wrap envelope from address */
1280                 /* FIXME: some parts of fetchmail don't handle null
1281                  * envelope senders, so use <> to mark null sender
1282                  * as a workaround. */
1283                 if (strspn(buf, " \t") == strlen(buf))
1284                     strcpy(buf, "<>");
1285                 sdps_envfrom = xmalloc(strlen(buf)+1);
1286                 strcpy(sdps_envfrom,buf);
1287                 break;
1288             case 5:
1289                 /* Wrap address with To: <> so nxtaddr() likes it */
1290                 sdps_envto = xmalloc(strlen(buf)+7);
1291                 sprintf(sdps_envto,"To: <%s>",buf);
1292                 break;
1293             }
1294         } while
1295             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1296     }
1297 #else
1298     (void)ctl;
1299 #endif /* SDPS_ENABLE */
1300
1301     /*
1302      * Though the POP RFCs don't document this fact, on almost every
1303      * POP3 server I know of messages are marked "seen" only at the
1304      * time the OK response to a RETR is issued.
1305      *
1306      * This means we can use TOP to fetch the message without setting its
1307      * seen flag.  This is good!  It means that if the protocol exchange
1308      * craps out during the message, it will still be marked `unseen' on
1309      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1310      * reported to mark messages seen on a TOP fetch.)
1311      *
1312      * However...*don't* do this if we're using keep to suppress deletion!
1313      * In that case, marking the seen flag is the only way to prevent the
1314      * message from being re-fetched on subsequent runs.
1315      *
1316      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1317      * This gives us a workaround for servers like usa.net's that bungle
1318      * TOP.  It's pretty harmless because fetchall guarantees that any
1319      * message dropped by an interrupted RETR will be picked up on the
1320      * next poll of the site.
1321      *
1322      * We take advantage here of the fact that, according to all the
1323      * POP RFCs, "if the number of lines requested by the POP3 client
1324      * is greater than than the number of lines in the body, then the
1325      * POP3 server sends the entire message.").
1326      *
1327      * The line count passed (99999999) is the maximum value CompuServe will
1328      * accept; it's much lower than the natural value 2147483646 (the maximum
1329      * twos-complement signed 32-bit integer minus 1) */
1330     if (!peek_capable)
1331         gen_send(sock, "RETR %d", number);
1332     else
1333         gen_send(sock, "TOP %d 99999999", number);
1334     if ((ok = pop3_ok(sock, buf)) != 0)
1335         return(ok);
1336
1337     *lenp = -1;         /* we got sizes from the LIST response */
1338
1339     return(PS_SUCCESS);
1340 }
1341
1342 static void mark_uid_seen(struct query *ctl, int number)
1343 /* Tell the UID code we've seen this. */
1344 {
1345     struct idlist       *sdp;
1346
1347     if ((sdp = id_find(&ctl->newsaved, number)))
1348         sdp->val.status.mark = UID_SEEN;
1349     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1350      * (say, due to socket error), the same mail will not be downloaded
1351      * again.
1352      */
1353     if ((sdp = id_find(&ctl->oldsaved, number)))
1354         sdp->val.status.mark = UID_SEEN;
1355 }
1356
1357 static int pop3_delete(int sock, struct query *ctl, int number)
1358 /* delete a given message */
1359 {
1360     int ok;
1361     mark_uid_seen(ctl, number);
1362     /* actually, mark for deletion -- doesn't happen until QUIT time */
1363     ok = gen_transact(sock, "DELE %d", number);
1364     if (ok != PS_SUCCESS)
1365         return(ok);
1366     delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1367     return(PS_SUCCESS);
1368 }
1369
1370 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1371 /* mark a given message as seen */
1372 {
1373     (void)sock;
1374     mark_uid_seen(ctl, number);
1375     return(PS_SUCCESS);
1376 }
1377
1378 static int pop3_logout(int sock, struct query *ctl)
1379 /* send logout command */
1380 {
1381     int ok;
1382
1383 #ifdef __UNUSED__
1384     /*
1385      * We used to do this in case the server marks messages deleted when seen.
1386      * (Yes, this has been reported, in the MercuryP/NLM server.
1387      * It's even legal under RFC 1939 (section 8) as a site policy.)
1388      * It interacted badly with UIDL, though.  Thomas Zajic wrote:
1389      * "Running 'fetchmail -F -v' and checking the logs, I found out
1390      * that fetchmail did in fact flush my mailbox properly, but sent
1391      * a RSET just before sending QUIT to log off.  This caused the
1392      * POP3 server to undo/forget about the previous DELEs, resetting
1393      * my mailbox to its original (ie.  unflushed) state. The
1394      * ~/.fetchids file did get flushed though, so the next time
1395      * fetchmail was run it saw all the old messages as new ones ..."
1396      */
1397      if (ctl->keep)
1398         gen_transact(sock, "RSET");
1399 #endif /* __UNUSED__ */
1400
1401     ok = gen_transact(sock, "QUIT");
1402     if (!ok)
1403         expunge_uids(ctl);
1404
1405     return(ok);
1406 }
1407
1408 static const struct method pop3 =
1409 {
1410     "POP3",             /* Post Office Protocol v3 */
1411     "pop3",             /* port for plain and TLS POP3 */
1412     "pop3s",            /* port for SSL POP3 */
1413     FALSE,              /* this is not a tagged protocol */
1414     TRUE,               /* this uses a message delimiter */
1415     pop3_ok,            /* parse command response */
1416     pop3_getauth,       /* get authorization */
1417     pop3_getrange,      /* query range of messages */
1418     pop3_getsizes,      /* we can get a list of sizes */
1419     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1420     pop3_is_old,        /* how do we tell a message is old? */
1421     pop3_fetch,         /* request given message */
1422     NULL,               /* no way to fetch body alone */
1423     NULL,               /* no message trailer */
1424     pop3_delete,        /* how to delete a message */
1425     pop3_mark_seen,     /* how to mark a message as seen */
1426     NULL,               /* no action at end of mailbox */
1427     pop3_logout,        /* log out, we're done */
1428     FALSE,              /* no, we can't re-poll */
1429 };
1430
1431 int doPOP3 (struct query *ctl)
1432 /* retrieve messages using POP3 */
1433 {
1434 #ifndef MBOX
1435     if (ctl->mailboxes->id) {
1436         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1437         return(PS_SYNTAX);
1438     }
1439 #endif /* MBOX */
1440
1441     return(do_protocol(ctl, &pop3));
1442 }
1443 #endif /* POP3_ENABLE */
1444
1445 /* pop3.c ends here */