]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Record POT regeneration date.
[~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
10 #ifdef POP3_ENABLE
11 #include  <stdio.h>
12 #include  <string.h>
13 #include  <ctype.h>
14 #if defined(HAVE_UNISTD_H)
15 #include <unistd.h>
16 #endif
17 #if defined(STDC_HEADERS)
18 #include  <stdlib.h>
19 #endif
20 #include  <errno.h>
21
22 #include  "fetchmail.h"
23 #include  "socket.h"
24 #include  "i18n.h"
25 #include  "uid_db.h"
26
27 #ifdef OPIE_ENABLE
28 #ifdef __cplusplus
29 extern "C" {
30 #endif
31 #include <opie.h>
32 #ifdef __cplusplus
33 }
34 #endif
35 #endif /* OPIE_ENABLE */
36
37 /* global variables: please reinitialize them explicitly for proper
38  * working in daemon mode */
39
40 /* TODO: session variables to be initialized before server greeting */
41 #ifdef OPIE_ENABLE
42 static char lastok[POPBUFSIZE+1];
43 #endif /* OPIE_ENABLE */
44
45 /* session variables initialized in capa_probe() or pop3_getauth() */
46 flag done_capa = FALSE;
47 #if defined(GSSAPI)
48 flag has_gssapi = FALSE;
49 #endif /* defined(GSSAPI) */
50 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
51 flag has_kerberos = FALSE;
52 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
53 static flag has_cram = FALSE;
54 #ifdef OPIE_ENABLE
55 flag has_otp = FALSE;
56 #endif /* OPIE_ENABLE */
57 #ifdef NTLM_ENABLE
58 flag has_ntlm = FALSE;
59 #endif /* NTLM_ENABLE */
60 #ifdef SSL_ENABLE
61 static flag has_stls = FALSE;
62 #endif /* SSL_ENABLE */
63
64 /* mailbox variables initialized in pop3_getrange() */
65 static int last;
66
67 /* mail variables initialized in pop3_fetch() */
68 #ifdef SDPS_ENABLE
69 char *sdps_envfrom;
70 char *sdps_envto;
71 #endif /* SDPS_ENABLE */
72
73 #ifdef NTLM_ENABLE
74 #include "ntlm.h"
75
76 /*
77  * NTLM support by Grant Edwards.
78  *
79  * Handle MS-Exchange NTLM authentication method.  This is the same
80  * as the NTLM auth used by Samba for SMB related services. We just
81  * encode the packets in base64 instead of sending them out via a
82  * network interface.
83  * 
84  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
85  */
86
87 static int do_pop3_ntlm(int sock, struct query *ctl,
88         int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
89 {
90     char msgbuf[POPBUFSIZE+1];
91     int result;
92
93     gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
94
95     if ((result = ntlm_helper(sock, ctl, "POP3")))
96         return result;
97
98     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
99         return result;
100
101     if (strstr (msgbuf, "OK"))
102         return PS_SUCCESS;
103     else
104         return PS_AUTHFAIL;
105 }
106 #endif /* NTLM */
107
108
109 #define DOTLINE(s)      (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
110
111 static int pop3_ok (int sock, char *argbuf)
112 /* parse command response */
113 {
114     int ok;
115     char buf [POPBUFSIZE+1];
116     char *bufp;
117
118     if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
119     {   bufp = buf;
120         if (*bufp == '+' || *bufp == '-')
121             bufp++;
122         else
123             return(PS_PROTOCOL);
124
125         while (isalpha((unsigned char)*bufp))
126             bufp++;
127
128         if (*bufp)
129           *(bufp++) = '\0';
130
131         if (strcmp(buf,"+OK") == 0)
132         {
133 #ifdef OPIE_ENABLE
134             strcpy(lastok, bufp);
135 #endif /* OPIE_ENABLE */
136             ok = 0;
137         }
138         else if (strncmp(buf,"-ERR", 4) == 0)
139         {
140             if (stage == STAGE_FETCH)
141                 ok = PS_TRANSIENT;
142             else if (stage > STAGE_GETAUTH)
143                 ok = PS_PROTOCOL;
144             /*
145              * We're checking for "lock busy", "unable to lock", 
146              * "already locked", "wait a few minutes" etc. here. 
147              * This indicates that we have to wait for the server to
148              * unwedge itself before we can poll again.
149              *
150              * PS_LOCKBUSY check empirically verified with two recent
151              * versions of the Berkeley popper; QPOP (version 2.2)  and
152              * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
153              * These are caught by the case-indifferent "lock" check.
154              * The "wait" catches "mail storage services unavailable,
155              * wait a few minutes and try again" on the InterMail server.
156              *
157              * If these aren't picked up on correctly, fetchmail will 
158              * think there is an authentication failure and wedge the
159              * connection in order to prevent futile polls.
160              *
161              * Gad, what a kluge.
162              */
163             else if (strstr(bufp,"lock")
164                      || strstr(bufp,"Lock")
165                      || strstr(bufp,"LOCK")
166                      || strstr(bufp,"wait")
167                      /* these are blessed by RFC 2449 */
168                      || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
169                 ok = PS_LOCKBUSY;
170             else if ((strstr(bufp,"Service")
171                      || strstr(bufp,"service"))
172                          && (strstr(bufp,"unavailable")))
173                 ok = PS_SERVBUSY;
174             else
175                 ok = PS_AUTHFAIL;
176             /*
177              * We always want to pass the user lock-busy messages, because
178              * they're red flags.  Other stuff (like AUTH failures on non-
179              * RFC1734 servers) only if we're debugging.
180              */
181             if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
182               report(stderr, "%s\n", bufp);
183         }
184         else
185             ok = PS_PROTOCOL;
186
187 #if POPBUFSIZE > MSGBUFSIZE
188 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
189 #endif
190         if (argbuf != NULL)
191             strcpy(argbuf,bufp);
192     }
193
194     return(ok);
195 }
196
197
198
199 static int capa_probe(int sock)
200 /* probe the capabilities of the remote server */
201 {
202     int ok;
203
204     if (done_capa) {
205         return PS_SUCCESS;
206     }
207 #if defined(GSSAPI)
208     has_gssapi = FALSE;
209 #endif /* defined(GSSAPI) */
210 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
211     has_kerberos = FALSE;
212 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
213     has_cram = FALSE;
214 #ifdef OPIE_ENABLE
215     has_otp = FALSE;
216 #endif /* OPIE_ENABLE */
217 #ifdef NTLM_ENABLE
218     has_ntlm = FALSE;
219 #endif /* NTLM_ENABLE */
220
221     ok = gen_transact(sock, "CAPA");
222     if (ok == PS_SUCCESS)
223     {
224         char buffer[64];
225
226         /* determine what authentication methods we have available */
227         while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
228         {
229             if (DOTLINE(buffer))
230                 break;
231
232 #ifdef SSL_ENABLE
233             if (strstr(buffer, "STLS"))
234                 has_stls = TRUE;
235 #endif /* SSL_ENABLE */
236
237 #if defined(GSSAPI)
238             if (strstr(buffer, "GSSAPI"))
239                 has_gssapi = TRUE;
240 #endif /* defined(GSSAPI) */
241
242 #if defined(KERBEROS_V4)
243             if (strstr(buffer, "KERBEROS_V4"))
244                 has_kerberos = TRUE;
245 #endif /* defined(KERBEROS_V4)  */
246
247 #ifdef OPIE_ENABLE
248             if (strstr(buffer, "X-OTP"))
249                 has_otp = TRUE;
250 #endif /* OPIE_ENABLE */
251
252 #ifdef NTLM_ENABLE
253             if (strstr(buffer, "NTLM"))
254                 has_ntlm = TRUE;
255 #endif /* NTLM_ENABLE */
256
257             if (strstr(buffer, "CRAM-MD5"))
258                 has_cram = TRUE;
259         }
260     }
261     done_capa = TRUE;
262     return(ok);
263 }
264
265 static void set_peek_capable(struct query *ctl)
266 {
267     /* we're peek-capable means that the use of TOP is enabled,
268      * see pop3_fetch for details - short story, we can use TOP if
269      * we have a means of reliably tracking which mail we need to
270      * refetch should the connection abort in the middle.
271      * fetchall forces RETR, as does keep without UIDL */
272     peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
273 }
274
275 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
276 /* apply for connection authorization */
277 {
278     int ok;
279     char *start,*end;
280     char *msg;
281 #ifdef OPIE_ENABLE
282     char *challenge;
283 #endif /* OPIE_ENABLE */
284 #ifdef SSL_ENABLE
285     flag connection_may_have_tls_errors = FALSE;
286     char *commonname;
287 #endif /* SSL_ENABLE */
288
289     done_capa = FALSE;
290 #if defined(GSSAPI)
291     has_gssapi = FALSE;
292 #endif /* defined(GSSAPI) */
293 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
294     has_kerberos = FALSE;
295 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
296     has_cram = FALSE;
297 #ifdef OPIE_ENABLE
298     has_otp = FALSE;
299 #endif /* OPIE_ENABLE */
300 #ifdef SSL_ENABLE
301     has_stls = FALSE;
302 #endif /* SSL_ENABLE */
303
304     /* Set this up before authentication quits early. */
305     set_peek_capable(ctl);
306
307     /* Hack: allow user to force RETR. */
308     if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
309         peek_capable = 0;
310     }
311
312     /*
313      * The "Maillennium POP3/PROXY server" deliberately truncates
314      * TOP replies after c. 64 or 80 kByte (we have varying reports), so
315      * disable TOP. Comcast once spewed marketing babble to the extent
316      * of protecting Outlook -- pretty overzealous to break a protocol
317      * for that that Microsoft could have read, too. Comcast aren't
318      * alone in using this software though.
319      * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
320      * (Thanks to Ed Wilts for reminding me of that.)
321      *
322      * The warning is printed once per server, until fetchmail exits.
323      * It will be suppressed when --fetchall or other circumstances make
324      * us use RETR anyhow.
325      *
326      * Matthias Andree
327      */
328     if (peek_capable && strstr(greeting, "Maillennium POP3")) {
329         if ((ctl->server.workarounds & WKA_TOP) == 0) {
330             report(stdout, GT_("Warning: \"Maillennium POP3\" found, using RETR command instead of TOP.\n"));
331             ctl->server.workarounds |= WKA_TOP;
332         }
333         peek_capable = 0;
334     }
335     if (ctl->server.authenticate == A_SSH) {
336         return PS_SUCCESS;
337     }
338
339 #ifdef SDPS_ENABLE
340     /*
341      * This needs to catch both demon.co.uk and demon.net.
342      * If we see either, and we're in multidrop mode, try to use
343      * the SDPS *ENV extension.
344      */
345     if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
346         ctl->server.sdps = TRUE;
347 #endif /* SDPS_ENABLE */
348
349    switch (ctl->server.protocol) {
350     case P_POP3:
351 #ifdef RPA_ENABLE
352         /* XXX FIXME: AUTH probing (RFC1734) should become global */
353         /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
354         if (strstr(ctl->remotename, "@compuserve.com"))
355         {
356             /* AUTH command should return a list of available mechanisms */
357             if (gen_transact(sock, "AUTH") == 0)
358             {
359                 char buffer[10];
360                 flag has_rpa = FALSE;
361
362                 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
363                 {
364                     if (DOTLINE(buffer))
365                         break;
366                     if (strncasecmp(buffer, "rpa", 3) == 0)
367                         has_rpa = TRUE;
368                 }
369                 if (has_rpa && !POP3_auth_rpa(ctl->remotename, 
370                                               ctl->password, sock))
371                     return(PS_SUCCESS);
372             }
373
374             return(PS_AUTHFAIL);
375         }
376 #endif /* RPA_ENABLE */
377
378         /*
379          * CAPA command may return a list including available
380          * authentication mechanisms and STLS capability.
381          *
382          * If it doesn't, no harm done, we just fall back to a plain
383          * login -- if the user allows it.
384          *
385          * Note that this code latches the server's authentication type,
386          * so that in daemon mode the CAPA check only needs to be done
387          * once at start of run.
388          *
389          * If CAPA fails, then force the authentication method to
390          * PASSWORD, switch off opportunistic and repoll immediately.
391          * If TLS is mandatory, fail up front.
392          */
393         if ((ctl->server.authenticate == A_ANY) ||
394                 (ctl->server.authenticate == A_GSSAPI) ||
395                 (ctl->server.authenticate == A_KERBEROS_V4) ||
396                 (ctl->server.authenticate == A_KERBEROS_V5) ||
397                 (ctl->server.authenticate == A_OTP) ||
398                 (ctl->server.authenticate == A_CRAM_MD5) ||
399                 maybe_starttls(ctl))
400         {
401             if ((ok = capa_probe(sock)) != PS_SUCCESS)
402                 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
403                 if (ok == PS_AUTHFAIL ||
404                     /* Some servers directly close the socket. However, if we
405                      * have already authenticated before, then a previous CAPA
406                      * must have succeeded. In that case, treat this as a
407                      * genuine socket error and do not change the auth method.
408                      */
409                     (ok == PS_SOCKET && !ctl->wehaveauthed))
410                 {
411 #ifdef SSL_ENABLE
412                     if (must_starttls(ctl)) {
413                         /* fail with mandatory STLS without repoll */
414                         report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
415                         report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
416                         return ok;
417                     } else if (maybe_starttls(ctl)) {
418                         /* defeat opportunistic STLS */
419                         xfree(ctl->sslproto);
420                         ctl->sslproto = xstrdup("");
421                     }
422 #endif
423                     /* If strong authentication was opportunistic, retry without, else fail. */
424                     switch (ctl->server.authenticate) {
425                         case A_ANY:
426                             ctl->server.authenticate = A_PASSWORD;
427                             /* FALLTHROUGH */
428                         case A_PASSWORD: /* this should only happen with TLS enabled */
429                             return PS_REPOLL;
430                         default:
431                             return PS_AUTHFAIL;
432                     }
433                 }
434         }
435
436 #ifdef SSL_ENABLE
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 (maybe_starttls(ctl)) {
444            if (has_stls || must_starttls(ctl)) /* if TLS is mandatory, ignore capabilities */
445            {
446                /* Don't need to worry whether TLS is mandatory or
447                 * opportunistic unless SSLOpen() fails (see below). */
448                if (gen_transact(sock, "STLS") == PS_SUCCESS
449                        && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, ctl->sslproto, ctl->sslcertck,
450                            ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
451                            ctl->server.pollname, &ctl->remotename)) != -1)
452                {
453                    /*
454                     * RFC 2595 says this:
455                     *
456                     * "Once TLS has been started, the client MUST discard cached
457                     * information about server capabilities and SHOULD re-issue the
458                     * CAPABILITY command.  This is necessary to protect against
459                     * man-in-the-middle attacks which alter the capabilities list prior
460                     * to STARTTLS.  The server MAY advertise different capabilities
461                     * after STARTTLS."
462                     *
463                     * Now that we're confident in our TLS connection we can
464                     * guarantee a secure capability re-probe.
465                     */
466                    set_timeout(0);
467                    done_capa = FALSE;
468                    ok = capa_probe(sock);
469                    if (ok != PS_SUCCESS) {
470                        return ok;
471                    }
472                    if (outlevel >= O_VERBOSE)
473                    {
474                        report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
475                    }
476                } else if (must_starttls(ctl)) {
477                    /* Config required TLS but we couldn't guarantee it, so we must
478                     * stop. */
479                    set_timeout(0);
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                    set_timeout(0);
489                    connection_may_have_tls_errors = TRUE;
490                    if (outlevel >= O_VERBOSE)
491                    {
492                        report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
493                    }
494                }
495            }
496         } else { /* maybe_starttls() */
497             if (has_stls && outlevel >= O_VERBOSE) {
498                 report(stdout, GT_("%s: WARNING: server offered STLS, but sslproto '' given.\n"), commonname);
499             }
500         } /* maybe_starttls() */
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     /* we're approved */
713     return(PS_SUCCESS);
714 }
715
716 /* cut off C string at first POSIX space */
717 static void trim(char *s) {
718     s += strcspn(s, POSIX_space);
719     s[0] = '\0';
720 }
721
722 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
723  * broken messages) do not have Message-ID headers, and messages without
724  * those appear to break this code and cause fetchmail (at least version
725  * 6.2.3) to not delete such messages properly after retrieval.
726  * See Sourceforge Bug #780933.
727  *
728  * The other problem is that the TOP command itself is optional, too... */
729 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
730 {
731     int ok;
732     int got_it;
733     char buf [POPBUFSIZE+1];
734     snprintf(buf, sizeof(buf), "TOP %d 1", num);
735     if ((ok = gen_transact(sock, "%s", buf)) != 0)
736        return ok;
737     got_it = 0;
738     while (gen_recv(sock, buf, sizeof(buf)) == 0)
739     {
740         if (DOTLINE(buf))
741             break;
742         if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
743             char *p = buf + 11;
744             got_it = 1;
745             p += strspn(p, POSIX_space);
746             strlcpy(id, p, idsize);
747             trim(id);
748         }
749     }
750     /* XXX FIXME: do not return success here if no Message-ID header was
751      * found. */
752     return 0;
753 }
754
755 /** Parse the UID response (leading +OK must have been
756  * stripped off) in buf, store the number in gotnum, and store the ID
757  * into the caller-provided buffer "id" of size "idsize".
758  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
759 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
760 {
761     const char *i;
762     char *j;
763
764     /* skip leading blanks ourselves */
765     i = buf;
766     i += strspn(i, POSIX_space);
767     errno = 0;
768     *gotnum = strtoul(i, &j, 10);
769     if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
770         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
771         return PS_PROTOCOL;
772     }
773     j += strspn(j, POSIX_space);
774     strlcpy(id, j, idsize);
775     trim(id);
776     return PS_SUCCESS;
777 }
778
779 /** request UIDL for single message \a num and stuff the result into the
780  * buffer \a id which can hold \a idsize bytes */
781 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
782 {
783     int ok;
784     char buf [POPBUFSIZE+1];
785     unsigned long gotnum;
786
787     gen_send(sock, "UIDL %d", num);
788     if ((ok = pop3_ok(sock, buf)) != 0)
789         return(ok);
790     if ((ok = parseuid(buf, &gotnum, id, idsize)))
791         return ok;
792     if (gotnum != (unsigned long)num) {
793         report(stderr, GT_("Server responded with UID for wrong message.\n"));
794         return PS_PROTOCOL;
795     }
796     return(PS_SUCCESS);
797 }
798
799 /** Do a binary search with single UIDL commands to find the first
800  * unseen message. */
801 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
802 {
803     int ok;
804     unsigned int first_nr, last_nr, try_nr;
805     char id [IDLEN+1];
806
807     first_nr = 0;
808     last_nr = count + 1;
809     while (first_nr < last_nr - 1)
810     {
811         struct uid_db_record *rec;
812
813         try_nr = (first_nr + last_nr) / 2;
814         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
815             return ok;
816         if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
817         {
818             flag mark = rec->status;
819             if (mark == UID_DELETED || mark == UID_EXPUNGED)
820             {
821                 if (outlevel >= O_VERBOSE)
822                     report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
823                 /* just mark it as seen now! */
824                 rec->status = mark = UID_SEEN;
825             }
826
827             /* narrow the search region! */
828             if (mark == UID_UNSEEN)
829             {
830                 if (outlevel >= O_DEBUG)
831                     report(stdout, GT_("%u is unseen\n"), try_nr);
832                 last_nr = try_nr;
833             }
834             else
835                 first_nr = try_nr;
836
837             /* save the number */
838             set_uid_db_num(&ctl->oldsaved, rec, try_nr);
839         }
840         else
841         {
842             if (outlevel >= O_DEBUG)
843                 report(stdout, GT_("%u is unseen\n"), try_nr);
844             last_nr = try_nr;
845
846             /* save it */
847             rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
848             set_uid_db_num(&ctl->oldsaved, rec, try_nr);
849         }
850     }
851     if (outlevel >= O_DEBUG && last_nr <= count)
852         report(stdout, GT_("%u is first unseen\n"), last_nr);
853
854     /* update last! */
855     *newp = count - first_nr;
856     last = first_nr;
857     return 0;
858 }
859
860 static int pop3_slowuidl( int sock,  struct query *ctl, int *countp, int *newp)
861 {
862     /* XXX FIXME: this code is severely broken. A Cc:d mailing list
863      * message will arrive twice with the same Message-ID, so this
864      * slowuidl code will break. Same goes for messages without
865      * Message-ID headers at all. This code would best be removed. */
866     /* This approach tries to get the message headers from the
867      * remote hosts and compares the message-id to the already known
868      * ones:
869      *  + if the first message containes a new id, all messages on
870      *    the server will be new
871      *  + if the first is known, try to estimate the last known message
872      *    on the server and check. If this works you know the total number
873      *    of messages to get.
874      *  + Otherwise run a binary search to determine the last known message
875      */
876     struct uid_db_record *rec;
877     int ok, nolinear = 0;
878     int first_nr, n_recs, try_id, try_nr, add_id;
879     int num;
880     char id [IDLEN+1];
881
882     if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
883         return ok;
884
885     rec = first_uid_in_db(&ctl->oldsaved, id);
886     if (!rec) {
887         /* the first message is unknown -> all messages are new */
888         *newp = *countp;        
889         return 0;
890     }
891     first_nr = rec->pos;
892
893     /* check where we expect the latest known message */
894     n_recs = uid_db_n_records(&ctl->oldsaved);
895     try_id = n_recs  - first_nr; /* -1 + 1 */
896     if( try_id > 1 ) {
897         if( try_id <= *countp ) {
898             if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
899                 return ok;
900
901             rec = last_uid_in_db(&ctl->oldsaved, id);
902             try_nr = rec ? (int)rec->pos : -1;
903         } else {
904             try_id = *countp+1;
905             try_nr = -1;
906         }
907         if( try_nr != n_recs -1 ) {
908             /* some messages inbetween have been deleted... */
909             if( try_nr == -1 ) {
910                 nolinear = 1;
911
912                 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
913                     ;
914                 for( ; add_id; add_id >>= 1 ) {
915                     if( try_nr == -1 ) {
916                         if( try_id - add_id <= 1 ) {
917                             continue;
918                         }
919                         try_id -= add_id;
920                     } else 
921                         try_id += add_id;
922                     
923                     if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
924                         return ok;
925
926                     rec = find_uid_by_id(&ctl->oldsaved, id);
927                     try_nr = rec ? (int)rec->pos : -1;
928                 }
929                 if( try_nr == -1 ) {
930                     try_id--;
931                 }
932             } else {
933                 report(stderr, 
934                        GT_("Messages inserted into list on server. Cannot handle this.\n"));
935                 return -1;
936             }
937         } 
938     }
939     /* the first try_id messages are known -> copy them to the newsaved list */
940     for( num = first_nr; num < n_recs; num++ )
941     {
942         rec = find_uid_by_pos(&ctl->oldsaved, num);
943
944         rec = uid_db_insert(&ctl->newsaved, rec->id, rec->status);
945         set_uid_db_num(&ctl->newsaved, rec, num - first_nr + 1);
946     }
947
948     if( nolinear ) {
949         clear_uid_db(&ctl->oldsaved);
950         last = try_id;
951     }
952
953     *newp = *countp - try_id;
954     return 0;
955 }
956
957 static int pop3_getrange(int sock, 
958                          struct query *ctl,
959                          const char *folder,
960                          int *countp, int *newp, int *bytes)
961 /* get range of messages to be fetched */
962 {
963     int ok;
964     char buf [POPBUFSIZE+1];
965
966     (void)folder;
967     /* Ensure that the new list is properly empty */
968     clear_uid_db(&ctl->newsaved);
969
970 #ifdef MBOX
971     /* Alain Knaff suggests this, but it's not RFC standard */
972     if (folder)
973         if ((ok = gen_transact(sock, "MBOX %s", folder)))
974             return ok;
975 #endif /* MBOX */
976
977     /* get the total message count */
978     gen_send(sock, "STAT");
979     ok = pop3_ok(sock, buf);
980     if (ok == 0) {
981         int asgn;
982
983         asgn = sscanf(buf,"%d %d", countp, bytes);
984         if (asgn != 2)
985                 return PS_PROTOCOL;
986     } else
987         return(ok);
988
989     /*
990      * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
991      * command.  We work as hard as possible to hide this, but it makes
992      * counting new messages intrinsically quadratic in the worst case.
993      */
994     last = 0;
995     *newp = -1;
996     /* if there are messages, and UIDL is desired, use UIDL
997      * also use UIDL if fetchall is unset */
998     if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
999     {
1000         int fastuidl;
1001         char id [IDLEN+1];
1002
1003         set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
1004         set_uid_db_num_pos_0(&ctl->newsaved, *countp);
1005
1006         /* should we do fast uidl this time? */
1007         fastuidl = ctl->fastuidl;
1008         if (*countp > 7 &&              /* linear search is better if there are few mails! */
1009             !ctl->fetchall &&           /* with fetchall, all uids are required */
1010             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
1011             NUM_NONZERO (fastuidl))
1012         {
1013             if (fastuidl == 1)
1014                 dofastuidl = 1;
1015             else
1016                 dofastuidl = ctl->fastuidlcount != 0;
1017         }
1018         else
1019             dofastuidl = 0;
1020
1021         if (!ctl->server.uidl) {
1022             gen_send(sock, "LAST");
1023             ok = pop3_ok(sock, buf);
1024         } else
1025             ok = 1;
1026
1027         if (ok == 0)
1028         {
1029             /* scan LAST reply */
1030             if (sscanf(buf, "%d", &last) == 0)
1031             {
1032                 report(stderr, GT_("protocol error\n"));
1033                 return(PS_ERROR);
1034             }
1035             *newp = (*countp - last);
1036         }
1037         else
1038         {
1039             /* do UIDL */
1040             if (dofastuidl)
1041                 return(pop3_fastuidl( sock, ctl, *countp, newp));
1042             /* grab the mailbox's UID list */
1043             if (gen_transact(sock, "UIDL") != 0)
1044             {
1045                 /* don't worry, yet! do it the slow way */
1046                 if (pop3_slowuidl(sock, ctl, countp, newp))
1047                 {
1048                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
1049                     return(PS_ERROR);
1050                 }
1051             }
1052             else
1053             {
1054                 /* UIDL worked - parse reply */
1055                 unsigned long unum;
1056
1057                 *newp = 0;
1058                 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
1059                 {
1060                     if (DOTLINE(buf))
1061                         break;
1062
1063                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1064                     {
1065                         struct uid_db_record    *old_rec, *new_rec;
1066
1067                         new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
1068
1069                         if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
1070                         {
1071                             flag mark = old_rec->status;
1072                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
1073                             {
1074                                 /* XXX FIXME: switch 3 occurrences from
1075                                  * (int)unum or (unsigned int)unum to
1076                                  * remove the cast and use %lu - not now
1077                                  * though, time for new release */
1078                                 if (outlevel >= O_VERBOSE)
1079                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1080                                 /* just mark it as seen now! */
1081                                 old_rec->status = mark = UID_SEEN;
1082                             }
1083                             new_rec->status = mark;
1084                             if (mark == UID_UNSEEN)
1085                             {
1086                                 (*newp)++;
1087                                 if (outlevel >= O_DEBUG)
1088                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1089                             }
1090                         }
1091                         else
1092                         {
1093                             (*newp)++;
1094                             if (outlevel >= O_DEBUG)
1095                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1096                             /* add it to oldsaved also! In case, we do not
1097                              * swap the lists (say, due to socket error),
1098                              * the same mail will not be downloaded again.
1099                              */
1100                             old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1101
1102                         }
1103                         /*
1104                          * save the number if it will be needed later on
1105                          * (messsage will either be fetched or deleted)
1106                          */
1107                         if (new_rec->status == UID_UNSEEN || ctl->flush) {
1108                             set_uid_db_num(&ctl->oldsaved, old_rec, unum);
1109                             set_uid_db_num(&ctl->newsaved, new_rec, unum);
1110                         }
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 uid_db_record *rec;
1180
1181     if (!uid_db_n_records(&ctl->oldsaved))
1182         return (num <= last);
1183     else if (dofastuidl)
1184     {
1185         char id [IDLEN+1];
1186
1187         if (num <= last)
1188             return(TRUE);
1189
1190         /* in fast uidl, we manipulate the old list only! */
1191
1192         if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1193         {
1194             /* we already have the id! */
1195             return(rec->status != UID_UNSEEN);
1196         }
1197
1198         /* get the uidl first! */
1199         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1200             return(TRUE);
1201
1202         if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1203             /* we already have the id! */
1204             set_uid_db_num(&ctl->oldsaved, rec, num);
1205             return(rec->status != UID_UNSEEN);
1206         }
1207
1208         /* save it */
1209         rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1210         set_uid_db_num(&ctl->oldsaved, rec, num);
1211
1212         return(FALSE);
1213     } else {
1214         rec = find_uid_by_num(&ctl->newsaved, num);
1215         return !rec || rec->status != UID_UNSEEN;
1216     }
1217 }
1218
1219 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1220 /* request nth message */
1221 {
1222     int ok;
1223     char buf[POPBUFSIZE+1];
1224
1225 #ifdef SDPS_ENABLE
1226     /*
1227      * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1228      * for a description of what we're parsing here.
1229      * -- updated 2006-02-22
1230      */
1231     if (ctl->server.sdps)
1232     {
1233         int     linecount = 0;
1234
1235         sdps_envfrom = (char *)NULL;
1236         sdps_envto = (char *)NULL;
1237         gen_send(sock, "*ENV %d", number);
1238         do {
1239             if (gen_recv(sock, buf, sizeof(buf)))
1240             {
1241                 break;
1242             }
1243             linecount++;
1244             switch (linecount) {
1245             case 4:
1246                 /* No need to wrap envelope from address */
1247                 /* FIXME: some parts of fetchmail don't handle null
1248                  * envelope senders, so use <> to mark null sender
1249                  * as a workaround. */
1250                 if (strspn(buf, " \t") == strlen(buf))
1251                     strcpy(buf, "<>");
1252                 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1253                 strcpy(sdps_envfrom,buf);
1254                 break;
1255             case 5:
1256                 /* Wrap address with To: <> so nxtaddr() likes it */
1257                 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1258                 sprintf(sdps_envto,"To: <%s>",buf);
1259                 break;
1260             }
1261         } while
1262             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1263     }
1264 #else
1265     (void)ctl;
1266 #endif /* SDPS_ENABLE */
1267
1268     /*
1269      * Though the POP RFCs don't document this fact, on almost every
1270      * POP3 server I know of messages are marked "seen" only at the
1271      * time the OK response to a RETR is issued.
1272      *
1273      * This means we can use TOP to fetch the message without setting its
1274      * seen flag.  This is good!  It means that if the protocol exchange
1275      * craps out during the message, it will still be marked `unseen' on
1276      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1277      * reported to mark messages seen on a TOP fetch.)
1278      *
1279      * However...*don't* do this if we're using keep to suppress deletion!
1280      * In that case, marking the seen flag is the only way to prevent the
1281      * message from being re-fetched on subsequent runs.
1282      *
1283      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1284      * This gives us a workaround for servers like usa.net's that bungle
1285      * TOP.  It's pretty harmless because fetchall guarantees that any
1286      * message dropped by an interrupted RETR will be picked up on the
1287      * next poll of the site.
1288      *
1289      * We take advantage here of the fact that, according to all the
1290      * POP RFCs, "if the number of lines requested by the POP3 client
1291      * is greater than than the number of lines in the body, then the
1292      * POP3 server sends the entire message.").
1293      *
1294      * The line count passed (99999999) is the maximum value CompuServe will
1295      * accept; it's much lower than the natural value 2147483646 (the maximum
1296      * twos-complement signed 32-bit integer minus 1) */
1297     if (!peek_capable)
1298         gen_send(sock, "RETR %d", number);
1299     else
1300         gen_send(sock, "TOP %d 99999999", number);
1301     if ((ok = pop3_ok(sock, buf)) != 0)
1302         return(ok);
1303
1304     *lenp = -1;         /* we got sizes from the LIST response */
1305
1306     return(PS_SUCCESS);
1307 }
1308
1309 static void mark_uid_seen(struct query *ctl, int number)
1310 /* Tell the UID code we've seen this. */
1311 {
1312     struct uid_db_record *rec;
1313
1314     if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1315         rec->status = UID_SEEN;
1316     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1317      * (say, due to socket error), the same mail will not be downloaded
1318      * again.
1319      */
1320     if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1321         rec->status = UID_SEEN;
1322 }
1323
1324 static int pop3_delete(int sock, struct query *ctl, int number)
1325 /* delete a given message */
1326 {
1327     struct uid_db_record *rec;
1328     int ok;
1329     mark_uid_seen(ctl, number);
1330     /* actually, mark for deletion -- doesn't happen until QUIT time */
1331     ok = gen_transact(sock, "DELE %d", number);
1332     if (ok != PS_SUCCESS)
1333         return(ok);
1334
1335     if ((rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number)))
1336             rec->status = UID_DELETED;
1337
1338     return(PS_SUCCESS);
1339 }
1340
1341 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1342 /* mark a given message as seen */
1343 {
1344     (void)sock;
1345     mark_uid_seen(ctl, number);
1346     return(PS_SUCCESS);
1347 }
1348
1349 static int pop3_logout(int sock, struct query *ctl)
1350 /* send logout command */
1351 {
1352     int ok;
1353
1354     ok = gen_transact(sock, "QUIT");
1355     if (!ok)
1356         expunge_uids(ctl);
1357
1358     return(ok);
1359 }
1360
1361 static const struct method pop3 =
1362 {
1363     "POP3",             /* Post Office Protocol v3 */
1364     "pop3",             /* port for plain and TLS POP3 */
1365     "pop3s",            /* port for SSL POP3 */
1366     FALSE,              /* this is not a tagged protocol */
1367     TRUE,               /* this uses a message delimiter */
1368     pop3_ok,            /* parse command response */
1369     pop3_getauth,       /* get authorization */
1370     pop3_getrange,      /* query range of messages */
1371     pop3_getsizes,      /* we can get a list of sizes */
1372     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1373     pop3_is_old,        /* how do we tell a message is old? */
1374     pop3_fetch,         /* request given message */
1375     NULL,               /* no way to fetch body alone */
1376     NULL,               /* no message trailer */
1377     pop3_delete,        /* how to delete a message */
1378     pop3_mark_seen,     /* how to mark a message as seen */
1379     NULL,               /* no action at end of mailbox */
1380     pop3_logout,        /* log out, we're done */
1381     FALSE,              /* no, we can't re-poll */
1382 };
1383
1384 int doPOP3 (struct query *ctl)
1385 /* retrieve messages using POP3 */
1386 {
1387 #ifndef MBOX
1388     if (ctl->mailboxes->id) {
1389         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1390         return(PS_SYNTAX);
1391     }
1392 #endif /* MBOX */
1393
1394     return(do_protocol(ctl, &pop3));
1395 }
1396 #endif /* POP3_ENABLE */
1397
1398 /* pop3.c ends here */