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