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