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