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