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