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