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