]> Pileus Git - ~andy/fetchmail/blob - pop3.c
Ignore UIDL failures if fetchall is on.
[~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                 if (!ctl->fetchall) {
867                     report(stderr, GT_("protocol error while fetching UIDLs\n"));
868                     return(PS_ERROR);
869                 }
870             }
871             else
872             {
873                 /* UIDL worked - parse reply */
874                 unsigned long unum;
875
876                 *newp = 0;
877                 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
878                 {
879                     if (DOTLINE(buf))
880                         break;
881
882                     if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
883                     {
884                         struct uid_db_record    *old_rec, *new_rec;
885
886                         new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
887
888                         if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
889                         {
890                             flag mark = old_rec->status;
891                             if (mark == UID_DELETED || mark == UID_EXPUNGED)
892                             {
893                                 /* XXX FIXME: switch 3 occurrences from
894                                  * (int)unum or (unsigned int)unum to
895                                  * remove the cast and use %lu - not now
896                                  * though, time for new release */
897                                 if (outlevel >= O_VERBOSE)
898                                     report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
899                                 /* just mark it as seen now! */
900                                 old_rec->status = mark = UID_SEEN;
901                             }
902                             new_rec->status = mark;
903                             if (mark == UID_UNSEEN)
904                             {
905                                 (*newp)++;
906                                 if (outlevel >= O_DEBUG)
907                                     report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
908                             }
909                         }
910                         else
911                         {
912                             (*newp)++;
913                             if (outlevel >= O_DEBUG)
914                                 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
915                             /* add it to oldsaved also! In case, we do not
916                              * swap the lists (say, due to socket error),
917                              * the same mail will not be downloaded again.
918                              */
919                             old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
920
921                         }
922                         /* save the number */
923                         if (new_rec->status == UID_UNSEEN || !ctl->keep) {
924                             set_uid_db_num(&ctl->oldsaved, old_rec, unum);
925                             set_uid_db_num(&ctl->newsaved, new_rec, unum);
926                         }
927                     } else
928                         return PS_ERROR;
929                 } /* multi-line loop for UIDL reply */
930             } /* UIDL parser */
931         } /* do UIDL */
932     }
933
934     return(PS_SUCCESS);
935 }
936
937 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
938 /* capture the size of message #first */
939 {
940     int ok = 0, i, num;
941     char buf [POPBUFSIZE+1];
942     unsigned int size;
943
944     for (i = first; i <= last; i++) {
945         gen_send(sock, "LIST %d", i);
946         if ((ok = pop3_ok(sock, buf)) != 0)
947             return(ok);
948         if (sscanf(buf, "%d %u", &num, &size) == 2) {
949             if (num == i)
950                 sizes[i - first] = size;
951             else
952                 /* warn about possible attempt to induce buffer overrun
953                  *
954                  * we expect server reply message number and requested
955                  * message number to match */
956                 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
957         }
958     }
959     return(ok);
960 }
961
962 static int pop3_getsizes(int sock, int count, int *sizes)
963 /* capture the sizes of all messages */
964 {
965     int ok;
966
967     if ((ok = gen_transact(sock, "LIST")) != 0)
968         return(ok);
969     else
970     {
971         char buf [POPBUFSIZE+1];
972
973         while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
974         {
975             unsigned int num, size;
976
977             if (DOTLINE(buf))
978                 break;
979             else if (sscanf(buf, "%u %u", &num, &size) == 2) {
980                 if (num > 0 && num <= (unsigned)count)
981                     sizes[num - 1] = size;
982                 else
983                     /* warn about possible attempt to induce buffer overrun */
984                     report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
985             }
986         }
987
988         return(ok);
989     }
990 }
991
992 static int pop3_is_old(int sock, struct query *ctl, int num)
993 /* is the given message old? */
994 {
995     struct uid_db_record *rec;
996
997     if (!uid_db_n_records(&ctl->oldsaved))
998         return (num <= last);
999     else if (dofastuidl)
1000     {
1001         char id [IDLEN+1];
1002
1003         if (num <= last)
1004             return(TRUE);
1005
1006         /* in fast uidl, we manipulate the old list only! */
1007         if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1008         {
1009             /* we already have the id! */
1010             return(rec->status != UID_UNSEEN);
1011         }
1012
1013         /* get the uidl first! */
1014         if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1015             return(TRUE);
1016
1017         if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1018             /* we already have the id! */
1019             set_uid_db_num(&ctl->oldsaved, rec, num);
1020             return(rec->status != UID_UNSEEN);
1021         }
1022
1023         /* save it */
1024         rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1025         set_uid_db_num(&ctl->oldsaved, rec, num);
1026
1027         return(FALSE);
1028     } else {
1029         rec = find_uid_by_num(&ctl->newsaved, num);
1030         return !rec || rec->status != UID_UNSEEN;
1031     }
1032 }
1033
1034 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1035 /* request nth message */
1036 {
1037     int ok;
1038     char buf[POPBUFSIZE+1];
1039
1040 #ifdef SDPS_ENABLE
1041     /*
1042      * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1043      * for a description of what we're parsing here.
1044      * -- updated 2006-02-22
1045      */
1046     if (ctl->server.sdps)
1047     {
1048         int     linecount = 0;
1049
1050         sdps_envfrom = (char *)NULL;
1051         sdps_envto = (char *)NULL;
1052         gen_send(sock, "*ENV %d", number);
1053         do {
1054             if (gen_recv(sock, buf, sizeof(buf)))
1055             {
1056                 break;
1057             }
1058             linecount++;
1059             switch (linecount) {
1060             case 4:
1061                 /* No need to wrap envelope from address */
1062                 /* FIXME: some parts of fetchmail don't handle null
1063                  * envelope senders, so use <> to mark null sender
1064                  * as a workaround. */
1065                 if (strspn(buf, " \t") == strlen(buf))
1066                     strcpy(buf, "<>");
1067                 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1068                 strcpy(sdps_envfrom,buf);
1069                 break;
1070             case 5:
1071                 /* Wrap address with To: <> so nxtaddr() likes it */
1072                 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1073                 sprintf(sdps_envto,"To: <%s>",buf);
1074                 break;
1075             }
1076         } while
1077             (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1078     }
1079 #else
1080     (void)ctl;
1081 #endif /* SDPS_ENABLE */
1082
1083     /*
1084      * Though the POP RFCs don't document this fact, on almost every
1085      * POP3 server I know of messages are marked "seen" only at the
1086      * time the OK response to a RETR is issued.
1087      *
1088      * This means we can use TOP to fetch the message without setting its
1089      * seen flag.  This is good!  It means that if the protocol exchange
1090      * craps out during the message, it will still be marked `unseen' on
1091      * the server.  (Exception: in early 1999 SpryNet's POP3 servers were
1092      * reported to mark messages seen on a TOP fetch.)
1093      *
1094      * However...*don't* do this if we're using keep to suppress deletion!
1095      * In that case, marking the seen flag is the only way to prevent the
1096      * message from being re-fetched on subsequent runs.
1097      *
1098      * Also use RETR (that means no TOP, no peek) if fetchall is on.
1099      * This gives us a workaround for servers like usa.net's that bungle
1100      * TOP.  It's pretty harmless because fetchall guarantees that any
1101      * message dropped by an interrupted RETR will be picked up on the
1102      * next poll of the site.
1103      *
1104      * We take advantage here of the fact that, according to all the
1105      * POP RFCs, "if the number of lines requested by the POP3 client
1106      * is greater than than the number of lines in the body, then the
1107      * POP3 server sends the entire message.").
1108      *
1109      * The line count passed (99999999) is the maximum value CompuServe will
1110      * accept; it's much lower than the natural value 2147483646 (the maximum
1111      * twos-complement signed 32-bit integer minus 1) */
1112     if (!peek_capable)
1113         gen_send(sock, "RETR %d", number);
1114     else
1115         gen_send(sock, "TOP %d 99999999", number);
1116     if ((ok = pop3_ok(sock, buf)) != 0)
1117         return(ok);
1118
1119     *lenp = -1;         /* we got sizes from the LIST response */
1120
1121     return(PS_SUCCESS);
1122 }
1123
1124 static void mark_uid_seen(struct query *ctl, int number)
1125 /* Tell the UID code we've seen this. */
1126 {
1127     struct uid_db_record *rec;
1128
1129     if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1130         rec->status = UID_SEEN;
1131     /* mark it as seen in oldsaved also! In case, we do not swap the lists
1132      * (say, due to socket error), the same mail will not be downloaded
1133      * again.
1134      */
1135     if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1136         rec->status = UID_SEEN;
1137 }
1138
1139 static int pop3_delete(int sock, struct query *ctl, int number)
1140 /* delete a given message */
1141 {
1142     struct uid_db_record *rec;
1143     int ok;
1144     mark_uid_seen(ctl, number);
1145     /* actually, mark for deletion -- doesn't happen until QUIT time */
1146     ok = gen_transact(sock, "DELE %d", number);
1147     if (ok != PS_SUCCESS)
1148         return(ok);
1149
1150     rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1151     rec->status = UID_DELETED;
1152     return(PS_SUCCESS);
1153 }
1154
1155 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1156 /* mark a given message as seen */
1157 {
1158     (void)sock;
1159     mark_uid_seen(ctl, number);
1160     return(PS_SUCCESS);
1161 }
1162
1163 static int pop3_logout(int sock, struct query *ctl)
1164 /* send logout command */
1165 {
1166     int ok;
1167
1168     ok = gen_transact(sock, "QUIT");
1169     if (!ok)
1170         expunge_uids(ctl);
1171
1172     return(ok);
1173 }
1174
1175 static const struct method pop3 =
1176 {
1177     "POP3",             /* Post Office Protocol v3 */
1178     "pop3",             /* port for plain and TLS POP3 */
1179     "pop3s",            /* port for SSL POP3 */
1180     FALSE,              /* this is not a tagged protocol */
1181     TRUE,               /* this uses a message delimiter */
1182     pop3_ok,            /* parse command response */
1183     pop3_getauth,       /* get authorization */
1184     pop3_getrange,      /* query range of messages */
1185     pop3_getsizes,      /* we can get a list of sizes */
1186     pop3_getpartialsizes,       /* we can get the size of 1 mail */
1187     pop3_is_old,        /* how do we tell a message is old? */
1188     pop3_fetch,         /* request given message */
1189     NULL,               /* no way to fetch body alone */
1190     NULL,               /* no message trailer */
1191     pop3_delete,        /* how to delete a message */
1192     pop3_mark_seen,     /* how to mark a message as seen */
1193     NULL,               /* no action at end of mailbox */
1194     pop3_logout,        /* log out, we're done */
1195     FALSE,              /* no, we can't re-poll */
1196 };
1197
1198 int doPOP3 (struct query *ctl)
1199 /* retrieve messages using POP3 */
1200 {
1201 #ifndef MBOX
1202     if (ctl->mailboxes->id) {
1203         fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1204         return(PS_SYNTAX);
1205     }
1206 #endif /* MBOX */
1207
1208     return(do_protocol(ctl, &pop3));
1209 }
1210 #endif /* POP3_ENABLE */
1211
1212 /* pop3.c ends here */