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