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