]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Drop LAST support, force UIDL.
[~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                        && 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                    done_capa = FALSE;
460                    ok = capa_probe(sock);
461                    if (ok != PS_SUCCESS) {
462                        return ok;
463                    }
464                    if (outlevel >= O_VERBOSE)
465                    {
466                        report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
467                    }
468                } else if (must_tls(ctl)) {
469                    /* Config required TLS but we couldn't guarantee it, so we must
470                     * stop. */
471                    report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
472                    return PS_SOCKET;
473                } else {
474                    /* We don't know whether the connection is usable, and there's
475                     * no command we can reasonably issue to test it (NOOP isn't
476                     * allowed til post-authentication), so leave it in an unknown
477                     * state, mark it as such, and check more carefully if things
478                     * go wrong when we try to authenticate. */
479                    connection_may_have_tls_errors = TRUE;
480                    if (outlevel >= O_VERBOSE)
481                    {
482                        report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
483                    }
484                }
485            }
486         } /* maybe_tls() */
487 #endif /* SSL_ENABLE */
488
489         /*
490          * OK, we have an authentication type now.
491          */
492
493 #if defined(GSSAPI)
494         if (has_gssapi &&
495             (ctl->server.authenticate == A_GSSAPI ||
496             (ctl->server.authenticate == A_ANY
497              && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
498         {
499             ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
500             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
501                 break;
502         }
503 #endif /* defined(GSSAPI) */
504
505 #ifdef OPIE_ENABLE
506         if (has_otp &&
507             (ctl->server.authenticate == A_OTP ||
508              ctl->server.authenticate == A_ANY))
509         {
510             ok = do_otp(sock, "AUTH", ctl);
511             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
512                 break;
513         }
514 #endif /* OPIE_ENABLE */
515
516 #ifdef NTLM_ENABLE
517     /* MSN servers require the use of NTLM (MSN) authentication */
518     if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
519             ctl->server.authenticate == A_MSN)
520         return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
521     if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
522         ok = do_pop3_ntlm(sock, ctl, 0);
523         if (ok == 0 || ctl->server.authenticate != A_ANY)
524             break;
525     }
526 #else
527     if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
528     {
529         report(stderr,
530            GT_("Required NTLM capability not compiled into fetchmail\n"));
531     }
532 #endif
533
534         if (ctl->server.authenticate == A_CRAM_MD5 || 
535             (has_cram && ctl->server.authenticate == A_ANY))
536         {
537             ok = do_cram_md5(sock, "AUTH", ctl, NULL);
538             if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
539                 break;
540         }
541
542         /* ordinary validation, no one-time password or RPA */ 
543         if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
544             break;
545
546 #ifdef OPIE_ENABLE
547         /* see RFC1938: A One-Time Password System */
548         if ((challenge = strstr(lastok, "otp-"))) {
549           char response[OPIE_RESPONSE_MAX+1];
550           int i;
551           char *n = xstrdup("");
552
553           i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
554           free(n);
555           if ((i == -2) && !run.poll_interval) {
556             char secret[OPIE_SECRET_MAX+1];
557             fprintf(stderr, GT_("Secret pass phrase: "));
558             if (opiereadpass(secret, sizeof(secret), 0))
559               i = opiegenerator(challenge,  secret, response);
560             memset(secret, 0, sizeof(secret));
561           };
562
563           if (i) {
564             ok = PS_ERROR;
565             break;
566           };
567
568           ok = gen_transact(sock, "PASS %s", response);
569           break;
570         }
571 #endif /* OPIE_ENABLE */
572
573         /* KPOP uses out-of-band authentication and does not check what
574          * we send here, so send some random fixed string, to avoid
575          * users switching *to* KPOP accidentally revealing their
576          * password */
577         if ((ctl->server.authenticate == A_ANY
578                     || ctl->server.authenticate == A_KERBEROS_V5)
579                 && (ctl->server.service != NULL
580                     && strcmp(ctl->server.service, KPOP_PORT) == 0))
581         {
582             ok = gen_transact(sock, "PASS krb_ticket");
583             break;
584         }
585
586         /* check if we are actually allowed to send the password */
587         if (ctl->server.authenticate == A_ANY
588                 || ctl->server.authenticate == A_PASSWORD) {
589             strlcpy(shroud, ctl->password, sizeof(shroud));
590             ok = gen_transact(sock, "PASS %s", ctl->password);
591         } else {
592             report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
593             ok = PS_AUTHFAIL;
594         }
595         memset(shroud, 0x55, sizeof(shroud));
596         shroud[0] = '\0';
597         break;
598
599     case P_APOP:
600         /* build MD5 digest from greeting timestamp + password */
601         /* find start of timestamp */
602         for (start = greeting;  *start != 0 && *start != '<';  start++)
603             continue;
604         if (*start == 0) {
605             report(stderr,
606                    GT_("Required APOP timestamp not found in greeting\n"));
607             return(PS_AUTHFAIL);
608         }
609
610         /* find end of timestamp */
611         for (end = start;  *end != 0  && *end != '>';  end++)
612             continue;
613         if (*end == 0 || end == start + 1) {
614             report(stderr, 
615                    GT_("Timestamp syntax error in greeting\n"));
616             return(PS_AUTHFAIL);
617         }
618         else
619             *++end = '\0';
620
621         /* SECURITY: 2007-03-17
622          * Strictly validating the presented challenge for RFC-822
623          * conformity (it must be a msg-id in terms of that standard) is
624          * supposed to make attacks against the MD5 implementation
625          * harder[1]
626          *
627          * [1] "Security vulnerability in APOP authentication",
628          *     Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
629         if (!rfc822_valid_msgid((unsigned char *)start)) {
630             report(stderr,
631                     GT_("Invalid APOP timestamp.\n"));
632             return PS_AUTHFAIL;
633         }
634
635         /* copy timestamp and password into digestion buffer */
636         msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
637         strcpy(msg,start);
638         strcat(msg,ctl->password);
639         strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
640         free(msg);
641
642         ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
643         break;
644
645     default:
646         report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
647         ok = PS_ERROR;
648     }
649
650 #ifdef SSL_ENABLE
651     /* this is for servers which claim to support TLS, but actually
652      * don't! */
653     if (connection_may_have_tls_errors
654                     && (ok == PS_SOCKET || ok == PS_PROTOCOL))
655     {
656         xfree(ctl->sslproto);
657         ctl->sslproto = xstrdup("");
658         /* repoll immediately without TLS */
659         ok = PS_REPOLL;
660     }
661 #endif
662
663     if (ok != 0)
664     {
665         /* maybe we detected a lock-busy condition? */
666         if (ok == PS_LOCKBUSY)
667             report(stderr, GT_("lock busy!  Is another session active?\n")); 
668
669         return(ok);
670     }
671
672 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
673  * accepted by Matthias Andree.
674  *
675  * Rationale: the server must have locked the spool before returning +OK;
676  * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
677 #ifdef WANT_BOGUS
678     /*
679      * Empirical experience shows some server/OS combinations
680      * may need a brief pause even after any lockfiles on the
681      * server are released, to give the server time to finish
682      * copying back very large mailfolders from the temp-file...
683      * this is only ever an issue with extremely large mailboxes.
684      */
685     sleep(3); /* to be _really_ safe, probably need sleep(5)! */
686 #endif
687
688     /* we're approved */
689     return(PS_SUCCESS);
690 }
691
692 /* cut off C string at first POSIX space */
693 static void trim(char *s) {
694     s += strcspn(s, POSIX_space);
695     s[0] = '\0';
696 }
697
698 /** Parse the UID response (leading +OK must have been
699  * stripped off) in buf, store the number in gotnum, and store the ID
700  * into the caller-provided buffer "id" of size "idsize".
701  * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
702 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
703 {
704     const char *i;
705     char *j;
706
707     /* skip leading blanks ourselves */
708     i = buf;
709     i += strspn(i, POSIX_space);
710     errno = 0;
711     *gotnum = strtoul(i, &j, 10);
712     if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
713         report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
714         return PS_PROTOCOL;
715     }
716     j += strspn(j, POSIX_space);
717     strlcpy(id, j, idsize);
718     trim(id);
719     return PS_SUCCESS;
720 }
721
722 /** request UIDL for single message \a num and stuff the result into the
723  * buffer \a id which can hold \a idsize bytes */
724 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
725 {
726     int ok;
727     char buf [POPBUFSIZE+1];
728     unsigned long gotnum;
729
730     gen_send(sock, "UIDL %d", num);
731     if ((ok = pop3_ok(sock, buf)) != 0)
732         return(ok);
733     if ((ok = parseuid(buf, &gotnum, id, idsize)))
734         return ok;
735     if (gotnum != (unsigned long)num) {
736         report(stderr, GT_("Server responded with UID for wrong message.\n"));
737         return PS_PROTOCOL;
738     }
739     return(PS_SUCCESS);
740 }
741
742 static int pop3_fastuidl( int sock,  struct query *ctl, unsigned int count, int *newp)
743 {
744     int ok;
745     unsigned int first_nr, last_nr, try_nr;
746     char id [IDLEN+1];
747
748     first_nr = 0;
749     last_nr = count + 1;
750     while (first_nr < last_nr - 1)
751     {
752         struct uid_db_record *rec;
753
754         try_nr = (first_nr + last_nr) / 2;
755         if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
756             return ok;
757         if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
758         {
759             flag mark = rec->status;
760             if (mark == UID_DELETED || mark == UID_EXPUNGED)
761             {
762                 if (outlevel >= O_VERBOSE)
763                     report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
764                 /* just mark it as seen now! */
765                 rec->status = mark = UID_SEEN;
766             }
767
768             /* narrow the search region! */
769             if (mark == UID_UNSEEN)
770             {
771                 if (outlevel >= O_DEBUG)
772                     report(stdout, GT_("%u is unseen\n"), try_nr);
773                 last_nr = try_nr;
774             }
775             else
776                 first_nr = try_nr;
777
778             /* save the number */
779             set_uid_db_num(&ctl->oldsaved, rec, try_nr);
780         }
781         else
782         {
783             if (outlevel >= O_DEBUG)
784                 report(stdout, GT_("%u is unseen\n"), try_nr);
785             last_nr = try_nr;
786
787             /* save it */
788             rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
789             set_uid_db_num(&ctl->oldsaved, rec, try_nr);
790         }
791     }
792     if (outlevel >= O_DEBUG && last_nr <= count)
793         report(stdout, GT_("%u is first unseen\n"), last_nr);
794
795     /* update last! */
796     *newp = count - first_nr;
797     last = first_nr;
798     return 0;
799 }
800
801 static int pop3_getrange(int sock, 
802                          struct query *ctl,
803                          const char *folder,
804                          int *countp, int *newp, int *bytes)
805 /* get range of messages to be fetched */
806 {
807     int ok;
808     char buf [POPBUFSIZE+1];
809
810     (void)folder;
811     /* Ensure that the new list is properly empty */
812     clear_uid_db(&ctl->newsaved);
813
814 #ifdef MBOX
815     /* Alain Knaff suggests this, but it's not RFC standard */
816     if (folder)
817         if ((ok = gen_transact(sock, "MBOX %s", folder)))
818             return ok;
819 #endif /* MBOX */
820
821     /* get the total message count */
822     gen_send(sock, "STAT");
823     ok = pop3_ok(sock, buf);
824     if (ok == 0) {
825         int asgn;
826
827         asgn = sscanf(buf,"%d %d", countp, bytes);
828         if (asgn != 2)
829                 return PS_PROTOCOL;
830     } else
831         return(ok);
832
833     /* unless fetching all mail, get UID list (UIDL) */
834     last = 0;
835     *newp = -1;
836     if (*countp > 0)
837     {
838         int fastuidl;
839         char id [IDLEN+1];
840
841         set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
842         set_uid_db_num_pos_0(&ctl->newsaved, *countp);
843
844         /* should we do fast uidl this time? */
845         fastuidl = ctl->fastuidl;
846         if (*countp > 7 &&              /* linear search is better if there are few mails! */
847             !ctl->fetchall &&           /* with fetchall, all uids are required */
848             !ctl->flush &&              /* with flush, it is safer to disable fastuidl */
849             NUM_NONZERO (fastuidl))
850         {
851             if (fastuidl == 1)
852                 dofastuidl = 1;
853             else
854                 dofastuidl = ctl->fastuidlcount != 0;
855         }
856         else
857             dofastuidl = 0;
858
859         {
860             /* do UIDL */
861             if (dofastuidl)
862                 return(pop3_fastuidl( sock, ctl, *countp, newp));
863             /* grab the mailbox's UID list */
864             if (gen_transact(sock, "UIDL") != 0)
865             {
866                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
867                     return(PS_ERROR);
868             }
869             else
870             {
871                 /* UIDL worked - parse reply */
872                 unsigned long unum;
873
874                 *newp = 0;
875                 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
876                 {
877                     if (DOTLINE(buf))
878                         break;
879
880                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
881                     {
882                         struct uid_db_record    *old_rec, *new_rec;
883
884                         new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
885
886                         if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
887                         {
888                             flag mark = old_rec->status;
889                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
890                             {
891                                 /* XXX FIXME: switch 3 occurrences from
892                                  * (int)unum or (unsigned int)unum to
893                                  * remove the cast and use %lu - not now
894                                  * though, time for new release */
895                                 if (outlevel >= O_VERBOSE)
896                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
897                                 /* just mark it as seen now! */
898                                 old_rec->status = mark = UID_SEEN;
899                             }
900                             new_rec->status = mark;
901                             if (mark == UID_UNSEEN)
902                             {
903                                 (*newp)++;
904                                 if (outlevel >= O_DEBUG)
905                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
906                             }
907                         }
908                         else
909                         {
910                             (*newp)++;
911                             if (outlevel >= O_DEBUG)
912                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
913                             /* add it to oldsaved also! In case, we do not
914                              * swap the lists (say, due to socket error),
915                              * the same mail will not be downloaded again.
916                              */
917                             old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
918
919                         }
920                         /* save the number */
921                         if (new_rec->status == UID_UNSEEN || !ctl->keep) {
922                             set_uid_db_num(&ctl->oldsaved, old_rec, unum);
923                             set_uid_db_num(&ctl->newsaved, new_rec, unum);
924                         }
925                     } else
926                         return PS_ERROR;
927                 } /* multi-line loop for UIDL reply */
928             } /* UIDL parser */
929         } /* do UIDL */
930     }
931
932     return(PS_SUCCESS);
933 }
934
935 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
936 /* capture the size of message #first */
937 {
938     int ok = 0, i, num;
939     char buf [POPBUFSIZE+1];
940     unsigned int size;
941
942     for (i = first; i <= last; i++) {
943         gen_send(sock, "LIST %d", i);
944         if ((ok = pop3_ok(sock, buf)) != 0)
945             return(ok);
946         if (sscanf(buf, "%d %u", &num, &size) == 2) {
947             if (num == i)
948                 sizes[i - first] = size;
949             else
950                 /* warn about possible attempt to induce buffer overrun
951                  *
952                  * we expect server reply message number and requested
953                  * message number to match */
954                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
955         }
956     }
957     return(ok);
958 }
959
960 static int pop3_getsizes(int sock, int count, int *sizes)
961 /* capture the sizes of all messages */
962 {
963     int ok;
964
965     if ((ok = gen_transact(sock, "LIST")) != 0)
966         return(ok);
967     else
968     {
969         char buf [POPBUFSIZE+1];
970
971         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
972         {
973             unsigned int num, size;
974
975             if (DOTLINE(buf))
976                 break;
977             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
978                 if (num > 0 && num <= (unsigned)count)
979                     sizes[num - 1] = size;
980                 else
981                     /* warn about possible attempt to induce buffer overrun */
982                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
983             }
984         }
985
986         return(ok);
987     }
988 }
989
990 static int pop3_is_old(int sock, struct query *ctl, int num)
991 /* is the given message old? */
992 {
993     struct uid_db_record *rec;
994
995     if (!uid_db_n_records(&ctl->oldsaved))
996         return (num <= last);
997     else if (dofastuidl)
998     {
999         char id [IDLEN+1];
1000
1001         if (num <= last)
1002             return(TRUE);
1003
1004         /* in fast uidl, we manipulate the old list only! */
1005         if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1006         {
1007             /* we already have the id! */
1008             return(rec->status != UID_UNSEEN);
1009         }
1010
1011         /* get the uidl first! */
1012         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1013             return(TRUE);
1014
1015         if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1016             /* we already have the id! */
1017             set_uid_db_num(&ctl->oldsaved, rec, num);
1018             return(rec->status != UID_UNSEEN);
1019         }
1020
1021         /* save it */
1022         rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1023         set_uid_db_num(&ctl->oldsaved, rec, num);
1024
1025         return(FALSE);
1026     } else {
1027         rec = find_uid_by_num(&ctl->newsaved, num);
1028         return !rec || rec->status != UID_UNSEEN;
1029     }
1030 }
1031
1032 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1033 /* request nth message */
1034 {
1035     int ok;
1036     char buf[POPBUFSIZE+1];
1037
1038 #ifdef SDPS_ENABLE
1039     /*
1040      * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1041      * for a description of what we're parsing here.
1042      * -- updated 2006-02-22
1043      */
1044     if (ctl->server.sdps)
1045     {
1046         int     linecount = 0;
1047
1048         sdps_envfrom = (char *)NULL;
1049         sdps_envto = (char *)NULL;
1050         gen_send(sock, "*ENV %d", number);
1051         do {
1052             if (gen_recv(sock, buf, sizeof(buf)))
1053             {
1054                 break;
1055             }
1056             linecount++;
1057             switch (linecount) {
1058             case 4:
1059                 /* No need to wrap envelope from address */
1060                 /* FIXME: some parts of fetchmail don't handle null
1061                  * envelope senders, so use <> to mark null sender
1062                  * as a workaround. */
1063                 if (strspn(buf, " \t") == strlen(buf))
1064                     strcpy(buf, "<>");
1065                 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1066                 strcpy(sdps_envfrom,buf);
1067                 break;
1068             case 5:
1069                 /* Wrap address with To: <> so nxtaddr() likes it */
1070                 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1071                 sprintf(sdps_envto,"To: <%s>",buf);
1072                 break;
1073             }
1074         } while
1075             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1076     }
1077 #else
1078     (void)ctl;
1079 #endif /* SDPS_ENABLE */
1080
1081     /*
1082      * Though the POP RFCs don't document this fact, on almost every
1083      * POP3 server I know of messages are marked "seen" only at the
1084      * time the OK response to a RETR is issued.
1085      *
1086      * This means we can use TOP to fetch the message without setting its
1087      * seen flag.  This is good!  It means that if the protocol exchange
1088      * craps out during the message, it will still be marked `unseen' on
1089      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1090      * reported to mark messages seen on a TOP fetch.)
1091      *
1092      * However...*don't* do this if we're using keep to suppress deletion!
1093      * In that case, marking the seen flag is the only way to prevent the
1094      * message from being re-fetched on subsequent runs.
1095      *
1096      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1097      * This gives us a workaround for servers like usa.net's that bungle
1098      * TOP.  It's pretty harmless because fetchall guarantees that any
1099      * message dropped by an interrupted RETR will be picked up on the
1100      * next poll of the site.
1101      *
1102      * We take advantage here of the fact that, according to all the
1103      * POP RFCs, "if the number of lines requested by the POP3 client
1104      * is greater than than the number of lines in the body, then the
1105      * POP3 server sends the entire message.").
1106      *
1107      * The line count passed (99999999) is the maximum value CompuServe will
1108      * accept; it's much lower than the natural value 2147483646 (the maximum
1109      * twos-complement signed 32-bit integer minus 1) */
1110     if (!peek_capable)
1111         gen_send(sock, "RETR %d", number);
1112     else
1113         gen_send(sock, "TOP %d 99999999", number);
1114     if ((ok = pop3_ok(sock, buf)) != 0)
1115         return(ok);
1116
1117     *lenp = -1;         /* we got sizes from the LIST response */
1118
1119     return(PS_SUCCESS);
1120 }
1121
1122 static void mark_uid_seen(struct query *ctl, int number)
1123 /* Tell the UID code we've seen this. */
1124 {
1125     struct uid_db_record *rec;
1126
1127     if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1128         rec->status = UID_SEEN;
1129     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1130      * (say, due to socket error), the same mail will not be downloaded
1131      * again.
1132      */
1133     if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1134         rec->status = UID_SEEN;
1135 }
1136
1137 static int pop3_delete(int sock, struct query *ctl, int number)
1138 /* delete a given message */
1139 {
1140     struct uid_db_record *rec;
1141     int ok;
1142     mark_uid_seen(ctl, number);
1143     /* actually, mark for deletion -- doesn't happen until QUIT time */
1144     ok = gen_transact(sock, "DELE %d", number);
1145     if (ok != PS_SUCCESS)
1146         return(ok);
1147
1148     rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1149     rec->status = UID_DELETED;
1150     return(PS_SUCCESS);
1151 }
1152
1153 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1154 /* mark a given message as seen */
1155 {
1156     (void)sock;
1157     mark_uid_seen(ctl, number);
1158     return(PS_SUCCESS);
1159 }
1160
1161 static int pop3_logout(int sock, struct query *ctl)
1162 /* send logout command */
1163 {
1164     int ok;
1165
1166     ok = gen_transact(sock, "QUIT");
1167     if (!ok)
1168         expunge_uids(ctl);
1169
1170     return(ok);
1171 }
1172
1173 static const struct method pop3 =
1174 {
1175     "POP3",             /* Post Office Protocol v3 */
1176     "pop3",             /* port for plain and TLS POP3 */
1177     "pop3s",            /* port for SSL POP3 */
1178     FALSE,              /* this is not a tagged protocol */
1179     TRUE,               /* this uses a message delimiter */
1180     pop3_ok,            /* parse command response */
1181     pop3_getauth,       /* get authorization */
1182     pop3_getrange,      /* query range of messages */
1183     pop3_getsizes,      /* we can get a list of sizes */
1184     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1185     pop3_is_old,        /* how do we tell a message is old? */
1186     pop3_fetch,         /* request given message */
1187     NULL,               /* no way to fetch body alone */
1188     NULL,               /* no message trailer */
1189     pop3_delete,        /* how to delete a message */
1190     pop3_mark_seen,     /* how to mark a message as seen */
1191     NULL,               /* no action at end of mailbox */
1192     pop3_logout,        /* log out, we're done */
1193     FALSE,              /* no, we can't re-poll */
1194 };
1195
1196 int doPOP3 (struct query *ctl)
1197 /* retrieve messages using POP3 */
1198 {
1199 #ifndef MBOX
1200     if (ctl->mailboxes->id) {
1201         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1202         return(PS_SYNTAX);
1203     }
1204 #endif /* MBOX */
1205
1206     return(do_protocol(ctl, &pop3));
1207 }
1208 #endif /* POP3_ENABLE */
1209
1210 /* pop3.c ends here */