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