2 * pop3.c -- POP3 protocol methods
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
13 #if defined(HAVE_UNISTD_H)
16 #if defined(STDC_HEADERS)
21 #include "fetchmail.h"
33 #endif /* OPIE_ENABLE */
35 /* global variables: please reinitialize them explicitly for proper
36 * working in daemon mode */
38 /* TODO: session variables to be initialized before server greeting */
40 static char lastok[POPBUFSIZE+1];
41 #endif /* OPIE_ENABLE */
43 /* session variables initialized in capa_probe() or pop3_getauth() */
44 flag done_capa = FALSE;
46 flag has_gssapi = FALSE;
47 #endif /* defined(GSSAPI) */
48 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
49 flag has_kerberos = FALSE;
50 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
51 static flag has_cram = FALSE;
54 #endif /* OPIE_ENABLE */
56 static flag has_stls = FALSE;
57 #endif /* SSL_ENABLE */
59 /* mailbox variables initialized in pop3_getrange() */
62 /* mail variables initialized in pop3_fetch() */
66 #endif /* SDPS_ENABLE */
72 * NTLM support by Grant Edwards.
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
79 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
82 static int do_pop3_ntlm(int sock, struct query *ctl,
83 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
85 tSmbNtlmAuthRequest request;
86 tSmbNtlmAuthChallenge challenge;
87 tSmbNtlmAuthResponse response;
92 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
94 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
100 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
102 if (outlevel >= O_DEBUG)
103 dumpSmbNtlmAuthRequest(stdout, &request);
105 memset(msgbuf,0,sizeof msgbuf);
106 to64frombits (msgbuf, &request, SmbLength(&request));
108 if (outlevel >= O_MONITOR)
109 report(stdout, "POP3> %s\n", msgbuf);
111 strcat(msgbuf,"\r\n");
112 SockWrite (sock, msgbuf, strlen (msgbuf));
114 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
117 len = from64tobits (&challenge, msgbuf, sizeof(msgbuf));
119 if (outlevel >= O_DEBUG)
120 dumpSmbNtlmAuthChallenge(stdout, &challenge);
122 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
124 if (outlevel >= O_DEBUG)
125 dumpSmbNtlmAuthResponse(stdout, &response);
127 memset(msgbuf,0,sizeof msgbuf);
128 to64frombits (msgbuf, &response, SmbLength(&response));
130 if (outlevel >= O_MONITOR)
131 report(stdout, "POP3> %s\n", msgbuf);
133 strcat(msgbuf,"\r\n");
134 SockWrite (sock, msgbuf, strlen (msgbuf));
136 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
139 if (strstr (msgbuf, "OK"))
147 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
149 static int pop3_ok (int sock, char *argbuf)
150 /* parse command response */
153 char buf [POPBUFSIZE+1];
156 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
158 if (*bufp == '+' || *bufp == '-')
163 while (isalpha((unsigned char)*bufp))
169 if (strcmp(buf,"+OK") == 0)
172 strcpy(lastok, bufp);
173 #endif /* OPIE_ENABLE */
176 else if (strncmp(buf,"-ERR", 4) == 0)
178 if (stage == STAGE_FETCH)
180 else if (stage > STAGE_GETAUTH)
183 * We're checking for "lock busy", "unable to lock",
184 * "already locked", "wait a few minutes" etc. here.
185 * This indicates that we have to wait for the server to
186 * unwedge itself before we can poll again.
188 * PS_LOCKBUSY check empirically verified with two recent
189 * versions of the Berkeley popper; QPOP (version 2.2) and
190 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
191 * These are caught by the case-indifferent "lock" check.
192 * The "wait" catches "mail storage services unavailable,
193 * wait a few minutes and try again" on the InterMail server.
195 * If these aren't picked up on correctly, fetchmail will
196 * think there is an authentication failure and wedge the
197 * connection in order to prevent futile polls.
201 else if (strstr(bufp,"lock")
202 || strstr(bufp,"Lock")
203 || strstr(bufp,"LOCK")
204 || strstr(bufp,"wait")
205 /* these are blessed by RFC 2449 */
206 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
208 else if ((strstr(bufp,"Service")
209 || strstr(bufp,"service"))
210 && (strstr(bufp,"unavailable")))
215 * We always want to pass the user lock-busy messages, because
216 * they're red flags. Other stuff (like AUTH failures on non-
217 * RFC1734 servers) only if we're debugging.
219 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
220 report(stderr, "%s\n", bufp);
225 #if POPBUFSIZE > MSGBUFSIZE
226 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
237 static int capa_probe(int sock)
238 /* probe the capabilities of the remote server */
247 #endif /* defined(GSSAPI) */
248 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
249 has_kerberos = FALSE;
250 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
254 #endif /* OPIE_ENABLE */
256 ok = gen_transact(sock, "CAPA");
257 if (ok == PS_SUCCESS)
261 /* determine what authentication methods we have available */
262 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
267 if (strstr(buffer, "STLS"))
269 #endif /* SSL_ENABLE */
271 if (strstr(buffer, "GSSAPI"))
273 #endif /* defined(GSSAPI) */
274 #if defined(KERBEROS_V4)
275 if (strstr(buffer, "KERBEROS_V4"))
277 #endif /* defined(KERBEROS_V4) */
279 if (strstr(buffer, "X-OTP"))
281 #endif /* OPIE_ENABLE */
282 if (strstr(buffer, "CRAM-MD5"))
290 static void set_peek_capable(struct query *ctl)
292 /* we're peek-capable means that the use of TOP is enabled,
293 * see pop3_fetch for details - short story, we can use TOP if
294 * we have a means of reliably tracking which mail we need to
295 * refetch should the connection abort in the middle.
296 * fetchall forces RETR, as does keep without UIDL */
297 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
300 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
301 /* apply for connection authorization */
308 #endif /* OPIE_ENABLE */
310 char *realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
311 flag connection_may_have_tls_errors = FALSE;
312 flag got_tls = FALSE;
313 #endif /* SSL_ENABLE */
318 #endif /* defined(GSSAPI) */
319 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
320 has_kerberos = FALSE;
321 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
325 #endif /* OPIE_ENABLE */
328 #endif /* SSL_ENABLE */
330 /* Set this up before authentication quits early. */
331 set_peek_capable(ctl);
333 * The "Maillennium POP3/PROXY server" deliberately truncates
334 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
335 * disable TOP. Comcast once spewed marketing babble to the extent
336 * of protecting Outlook -- pretty overzealous to break a protocol
337 * for that that Microsoft could have read, too. Comcast aren't
338 * alone in using this software though.
339 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
340 * (Thanks to Ed Wilts for reminding me of that.)
342 * The warning is printed once per server, until fetchmail exits.
343 * It will be suppressed when --fetchall or other circumstances make
344 * us use RETR anyhow.
348 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
349 if ((ctl->server.workarounds & WKA_TOP) == 0) {
350 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
351 ctl->server.workarounds |= WKA_TOP;
355 if (ctl->server.authenticate == A_SSH) {
361 * This needs to catch both demon.co.uk and demon.net.
362 * If we see either, and we're in multidrop mode, try to use
363 * the SDPS *ENV extension.
365 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
366 ctl->server.sdps = TRUE;
367 #endif /* SDPS_ENABLE */
370 /* MSN servers require the use of NTLM (MSN) authentication */
371 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
372 ctl->server.authenticate == A_MSN)
373 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
374 if (ctl->server.authenticate == A_NTLM)
375 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
377 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
380 GT_("Required NTLM capability not compiled into fetchmail\n"));
384 switch (ctl->server.protocol) {
387 /* XXX FIXME: AUTH probing (RFC1734) should become global */
388 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
389 if (strstr(ctl->remotename, "@compuserve.com"))
391 /* AUTH command should return a list of available mechanisms */
392 if (gen_transact(sock, "AUTH") == 0)
395 flag has_rpa = FALSE;
397 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
401 if (strncasecmp(buffer, "rpa", 3) == 0)
404 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
405 ctl->password, sock))
411 #endif /* RPA_ENABLE */
414 * CAPA command may return a list including available
415 * authentication mechanisms and STLS capability.
417 * If it doesn't, no harm done, we just fall back to a plain
418 * login -- if the user allows it.
420 * Note that this code latches the server's authentication type,
421 * so that in daemon mode the CAPA check only needs to be done
422 * once at start of run.
424 * If CAPA fails, then force the authentication method to
425 * PASSWORD, switch off opportunistic and repoll immediately.
426 * If TLS is mandatory, fail up front.
428 if ((ctl->server.authenticate == A_ANY) ||
429 (ctl->server.authenticate == A_GSSAPI) ||
430 (ctl->server.authenticate == A_KERBEROS_V4) ||
431 (ctl->server.authenticate == A_KERBEROS_V5) ||
432 (ctl->server.authenticate == A_OTP) ||
433 (ctl->server.authenticate == A_CRAM_MD5) ||
436 if ((ok = capa_probe(sock)) != PS_SUCCESS)
437 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
438 if (ok == PS_AUTHFAIL ||
439 /* Some servers directly close the socket. However, if we
440 * have already authenticated before, then a previous CAPA
441 * must have succeeded. In that case, treat this as a
442 * genuine socket error and do not change the auth method.
444 (ok == PS_SOCKET && !ctl->wehaveauthed))
448 /* fail with mandatory STLS without repoll */
449 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
450 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
452 } else if (maybe_tls(ctl)) {
453 /* defeat opportunistic STLS */
454 xfree(ctl->sslproto);
455 ctl->sslproto = xstrdup("");
458 /* If strong authentication was opportunistic, retry without, else fail. */
459 switch (ctl->server.authenticate) {
461 ctl->server.authenticate = A_PASSWORD;
463 case A_PASSWORD: /* this should only happen with TLS enabled */
472 if (maybe_tls(ctl)) {
475 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
476 * protocol that will work with STARTTLS. Don't need to worry
477 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
479 if (gen_transact(sock, "STLS") == PS_SUCCESS
480 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
481 ctl->sslcertpath, ctl->sslfingerprint, realhost,
482 ctl->server.pollname, &ctl->remotename) != -1)
485 * RFC 2595 says this:
487 * "Once TLS has been started, the client MUST discard cached
488 * information about server capabilities and SHOULD re-issue the
489 * CAPABILITY command. This is necessary to protect against
490 * man-in-the-middle attacks which alter the capabilities list prior
491 * to STARTTLS. The server MAY advertise different capabilities
494 * Now that we're confident in our TLS connection we can
495 * guarantee a secure capability re-probe.
499 ok = capa_probe(sock);
500 if (ok != PS_SUCCESS) {
503 if (outlevel >= O_VERBOSE)
505 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), realhost);
512 /* Config required TLS but we couldn't guarantee it, so we must
514 report(stderr, GT_("%s: upgrade to TLS failed.\n"), realhost);
517 /* We don't know whether the connection is usable, and there's
518 * no command we can reasonably issue to test it (NOOP isn't
519 * allowed til post-authentication), so leave it in an unknown
520 * state, mark it as such, and check more carefully if things
521 * go wrong when we try to authenticate. */
522 connection_may_have_tls_errors = TRUE;
523 if (outlevel >= O_VERBOSE)
525 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), realhost);
530 #endif /* SSL_ENABLE */
533 * OK, we have an authentication type now.
535 #if defined(KERBEROS_V4)
537 * Servers doing KPOP have to go through a dummy login sequence
538 * rather than doing SASL.
541 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
542 && (ctl->server.authenticate == A_KERBEROS_V4
543 || ctl->server.authenticate == A_KERBEROS_V5
544 || ctl->server.authenticate == A_ANY))
546 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
547 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
550 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
554 (ctl->server.authenticate == A_GSSAPI ||
555 ctl->server.authenticate == A_ANY))
557 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
558 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
561 #endif /* defined(GSSAPI) */
565 (ctl->server.authenticate == A_OTP ||
566 ctl->server.authenticate == A_ANY))
568 ok = do_otp(sock, "AUTH", ctl);
569 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
572 #endif /* OPIE_ENABLE */
574 if (ctl->server.authenticate == A_CRAM_MD5 ||
575 (has_cram && ctl->server.authenticate == A_ANY))
577 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
578 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
582 /* ordinary validation, no one-time password or RPA */
583 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
587 /* see RFC1938: A One-Time Password System */
588 if ((challenge = strstr(lastok, "otp-"))) {
589 char response[OPIE_RESPONSE_MAX+1];
591 char *n = xstrdup("");
593 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
595 if ((i == -2) && !run.poll_interval) {
596 char secret[OPIE_SECRET_MAX+1];
597 fprintf(stderr, GT_("Secret pass phrase: "));
598 if (opiereadpass(secret, sizeof(secret), 0))
599 i = opiegenerator(challenge, secret, response);
600 memset(secret, 0, sizeof(secret));
608 ok = gen_transact(sock, "PASS %s", response);
611 #endif /* OPIE_ENABLE */
613 /* KPOP uses out-of-band authentication and does not check what
614 * we send here, so send some random fixed string, to avoid
615 * users switching *to* KPOP accidentally revealing their
617 if ((ctl->server.authenticate == A_ANY
618 || ctl->server.authenticate == A_KERBEROS_V4
619 || ctl->server.authenticate == A_KERBEROS_V5)
620 && (ctl->server.service != NULL
621 && strcmp(ctl->server.service, KPOP_PORT) == 0))
623 ok = gen_transact(sock, "PASS krb_ticket");
627 /* check if we are actually allowed to send the password */
628 if (ctl->server.authenticate == A_ANY
629 || ctl->server.authenticate == A_PASSWORD) {
630 strlcpy(shroud, ctl->password, sizeof(shroud));
631 ok = gen_transact(sock, "PASS %s", ctl->password);
633 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
636 memset(shroud, 0x55, sizeof(shroud));
641 /* build MD5 digest from greeting timestamp + password */
642 /* find start of timestamp */
643 for (start = greeting; *start != 0 && *start != '<'; start++)
647 GT_("Required APOP timestamp not found in greeting\n"));
651 /* find end of timestamp */
652 for (end = start; *end != 0 && *end != '>'; end++)
654 if (*end == 0 || end == start + 1) {
656 GT_("Timestamp syntax error in greeting\n"));
662 /* SECURITY: 2007-03-17
663 * Strictly validating the presented challenge for RFC-822
664 * conformity (it must be a msg-id in terms of that standard) is
665 * supposed to make attacks against the MD5 implementation
668 * [1] "Security vulnerability in APOP authentication",
669 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
670 if (!rfc822_valid_msgid((unsigned char *)start)) {
672 GT_("Invalid APOP timestamp.\n"));
676 /* copy timestamp and password into digestion buffer */
677 msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
679 strcat(msg,ctl->password);
680 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
683 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
687 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
688 strlcpy(shroud, ctl->password, sizeof(shroud));
689 ok = gen_transact(sock, "RPOP %s", ctl->password);
690 memset(shroud, 0x55, sizeof(shroud));
696 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
701 /* this is for servers which claim to support TLS, but actually
703 if (connection_may_have_tls_errors
704 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
706 xfree(ctl->sslproto);
707 ctl->sslproto = xstrdup("");
708 /* repoll immediately without TLS */
715 /* maybe we detected a lock-busy condition? */
716 if (ok == PS_LOCKBUSY)
717 report(stderr, GT_("lock busy! Is another session active?\n"));
722 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
723 * accepted by Matthias Andree.
725 * Rationale: the server must have locked the spool before returning +OK;
726 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
729 * Empirical experience shows some server/OS combinations
730 * may need a brief pause even after any lockfiles on the
731 * server are released, to give the server time to finish
732 * copying back very large mailfolders from the temp-file...
733 * this is only ever an issue with extremely large mailboxes.
735 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
742 /* cut off C string at first POSIX space */
743 static void trim(char *s) {
744 s += strcspn(s, POSIX_space);
748 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
749 * broken messages) do not have Message-ID headers, and messages without
750 * those appear to break this code and cause fetchmail (at least version
751 * 6.2.3) to not delete such messages properly after retrieval.
752 * See Sourceforge Bug #780933.
754 * The other problem is that the TOP command itself is optional, too... */
755 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
759 char buf [POPBUFSIZE+1];
760 snprintf(buf, sizeof(buf), "TOP %d 1", num);
761 if ((ok = gen_transact(sock, buf )) != 0)
764 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
768 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
771 p += strspn(p, POSIX_space);
772 strlcpy(id, p, idsize);
776 /* XXX FIXME: do not return success here if no Message-ID header was
781 /** Parse the UID response (leading +OK must have been
782 * stripped off) in buf, store the number in gotnum, and store the ID
783 * into the caller-provided buffer "id" of size "idsize".
784 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
785 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
790 /* skip leading blanks ourselves */
792 i += strspn(i, POSIX_space);
794 *gotnum = strtoul(i, &j, 10);
795 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
796 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
799 j += strspn(j, POSIX_space);
800 strlcpy(id, j, idsize);
805 /** request UIDL for single message \a num and stuff the result into the
806 * buffer \a id which can hold \a idsize bytes */
807 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
810 char buf [POPBUFSIZE+1];
811 unsigned long gotnum;
813 gen_send(sock, "UIDL %d", num);
814 if ((ok = pop3_ok(sock, buf)) != 0)
816 if ((ok = parseuid(buf, &gotnum, id, idsize)))
818 if (gotnum != (unsigned long)num) {
819 report(stderr, GT_("Server responded with UID for wrong message.\n"));
825 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
828 unsigned int first_nr, last_nr, try_nr;
833 while (first_nr < last_nr - 1)
837 try_nr = (first_nr + last_nr) / 2;
838 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
840 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
842 flag mark = newl->val.status.mark;
843 if (mark == UID_DELETED || mark == UID_EXPUNGED)
845 if (outlevel >= O_VERBOSE)
846 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
847 /* just mark it as seen now! */
848 newl->val.status.mark = mark = UID_SEEN;
851 /* narrow the search region! */
852 if (mark == UID_UNSEEN)
854 if (outlevel >= O_DEBUG)
855 report(stdout, GT_("%u is unseen\n"), try_nr);
861 /* save the number */
862 newl->val.status.num = try_nr;
866 if (outlevel >= O_DEBUG)
867 report(stdout, GT_("%u is unseen\n"), try_nr);
871 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
872 newl->val.status.num = try_nr;
875 if (outlevel >= O_DEBUG && last_nr <= count)
876 report(stdout, GT_("%u is first unseen\n"), last_nr);
879 *newp = count - first_nr;
884 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
886 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
887 * message will arrive twice with the same Message-ID, so this
888 * slowuidl code will break. Same goes for messages without
889 * Message-ID headers at all. This code would best be removed. */
890 /* This approach tries to get the message headers from the
891 * remote hosts and compares the message-id to the already known
893 * + if the first message containes a new id, all messages on
894 * the server will be new
895 * + if the first is known, try to estimate the last known message
896 * on the server and check. If this works you know the total number
897 * of messages to get.
898 * + Otherwise run a binary search to determine the last known message
900 int ok, nolinear = 0;
901 int first_nr, list_len, try_id, try_nr, add_id;
905 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
908 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
909 /* the first message is unknown -> all messages are new */
914 /* check where we expect the latest known message */
915 list_len = count_list( &ctl->oldsaved );
916 try_id = list_len - first_nr; /* -1 + 1 */
918 if( try_id <= *countp ) {
919 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
922 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
927 if( try_nr != list_len -1 ) {
928 /* some messages inbetween have been deleted... */
932 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
934 for( ; add_id; add_id >>= 1 ) {
936 if( try_id - add_id <= 1 ) {
943 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
945 try_nr = str_nr_in_list(&ctl->oldsaved, id);
952 GT_("Messages inserted into list on server. Cannot handle this.\n"));
957 /* the first try_id messages are known -> copy them to the newsaved list */
958 for( num = first_nr; num < list_len; num++ )
960 struct idlist *newl = save_str(&ctl->newsaved,
961 str_from_nr_list(&ctl->oldsaved, num),
963 newl->val.status.num = num - first_nr + 1;
967 free_str_list(&ctl->oldsaved);
972 *newp = *countp - try_id;
976 static int pop3_getrange(int sock,
979 int *countp, int *newp, int *bytes)
980 /* get range of messages to be fetched */
983 char buf [POPBUFSIZE+1];
986 /* Ensure that the new list is properly empty */
987 ctl->newsaved = (struct idlist *)NULL;
990 /* Alain Knaff suggests this, but it's not RFC standard */
992 if ((ok = gen_transact(sock, "MBOX %s", folder)))
996 /* get the total message count */
997 gen_send(sock, "STAT");
998 ok = pop3_ok(sock, buf);
1000 sscanf(buf,"%d %d", countp, bytes);
1005 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
1006 * command. We work as hard as possible to hide this, but it makes
1007 * counting new messages intrinsically quadratic in the worst case.
1011 /* if there are messages, and UIDL is desired, use UIDL
1012 * also use UIDL if fetchall is unset */
1013 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
1018 /* should we do fast uidl this time? */
1019 fastuidl = ctl->fastuidl;
1020 if (*countp > 7 && /* linear search is better if there are few mails! */
1021 !ctl->fetchall && /* with fetchall, all uids are required */
1022 !ctl->flush && /* with flush, it is safer to disable fastuidl */
1023 NUM_NONZERO (fastuidl))
1028 dofastuidl = ctl->fastuidlcount != 0;
1033 if (!ctl->server.uidl) {
1034 gen_send(sock, "LAST");
1035 ok = pop3_ok(sock, buf);
1041 /* scan LAST reply */
1042 if (sscanf(buf, "%d", &last) == 0)
1044 report(stderr, GT_("protocol error\n"));
1047 *newp = (*countp - last);
1053 return(pop3_fastuidl( sock, ctl, *countp, newp));
1054 /* grab the mailbox's UID list */
1055 if ((ok = gen_transact(sock, "UIDL")) != 0)
1057 /* don't worry, yet! do it the slow way */
1058 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
1060 report(stderr, GT_("protocol error while fetching UIDLs\n"));
1066 /* UIDL worked - parse reply */
1070 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
1075 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1077 struct idlist *old, *newl;
1079 newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
1080 newl->val.status.num = unum;
1082 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
1084 flag mark = old->val.status.mark;
1085 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1087 /* XXX FIXME: switch 3 occurrences from
1088 * (int)unum or (unsigned int)unum to
1089 * remove the cast and use %lu - not now
1090 * though, time for new release */
1091 if (outlevel >= O_VERBOSE)
1092 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1093 /* just mark it as seen now! */
1094 old->val.status.mark = mark = UID_SEEN;
1096 newl->val.status.mark = mark;
1097 if (mark == UID_UNSEEN)
1100 if (outlevel >= O_DEBUG)
1101 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1107 if (outlevel >= O_DEBUG)
1108 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1109 /* add it to oldsaved also! In case, we do not
1110 * swap the lists (say, due to socket error),
1111 * the same mail will not be downloaded again.
1113 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1115 /* save the number */
1116 old->val.status.num = unum;
1119 } /* multi-line loop for UIDL reply */
1127 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1128 /* capture the size of message #first */
1131 char buf [POPBUFSIZE+1];
1134 for (i = first; i <= last; i++) {
1135 gen_send(sock, "LIST %d", i);
1136 if ((ok = pop3_ok(sock, buf)) != 0)
1138 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1140 sizes[i - first] = size;
1142 /* warn about possible attempt to induce buffer overrun
1144 * we expect server reply message number and requested
1145 * message number to match */
1146 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1152 static int pop3_getsizes(int sock, int count, int *sizes)
1153 /* capture the sizes of all messages */
1157 if ((ok = gen_transact(sock, "LIST")) != 0)
1161 char buf [POPBUFSIZE+1];
1163 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1165 unsigned int num, size;
1169 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1170 if (num > 0 && num <= (unsigned)count)
1171 sizes[num - 1] = size;
1173 /* warn about possible attempt to induce buffer overrun */
1174 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1182 static int pop3_is_old(int sock, struct query *ctl, int num)
1183 /* is the given message old? */
1185 struct idlist *newl;
1187 return (num <= last);
1188 else if (dofastuidl)
1195 /* in fast uidl, we manipulate the old list only! */
1197 if ((newl = id_find(&ctl->oldsaved, num)))
1199 /* we already have the id! */
1200 return(newl->val.status.mark != UID_UNSEEN);
1203 /* get the uidl first! */
1204 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1207 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1208 /* we already have the id! */
1209 newl->val.status.num = num;
1210 return(newl->val.status.mark != UID_UNSEEN);
1214 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1215 newl->val.status.num = num;
1219 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1220 newl->val.status.mark != UID_UNSEEN);
1225 * We could use this to fetch headers only as we do for IMAP. The trouble
1226 * is that there's no way to fetch the body only. So the following RETR
1227 * would have to re-fetch the header. Enough messages have longer headers
1228 * than bodies to make this a net loss.
1230 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1231 /* request headers of nth message */
1234 char buf[POPBUFSIZE+1];
1236 gen_send(sock, "TOP %d 0", number);
1237 if ((ok = pop3_ok(sock, buf)) != 0)
1240 *lenp = -1; /* we got sizes from the LIST response */
1246 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1247 /* request nth message */
1250 char buf[POPBUFSIZE+1];
1254 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1255 * for a description of what we're parsing here.
1256 * -- updated 2006-02-22
1258 if (ctl->server.sdps)
1262 sdps_envfrom = (char *)NULL;
1263 sdps_envto = (char *)NULL;
1264 gen_send(sock, "*ENV %d", number);
1266 if (gen_recv(sock, buf, sizeof(buf)))
1271 switch (linecount) {
1273 /* No need to wrap envelope from address */
1274 /* FIXME: some parts of fetchmail don't handle null
1275 * envelope senders, so use <> to mark null sender
1276 * as a workaround. */
1277 if (strspn(buf, " \t") == strlen(buf))
1279 sdps_envfrom = xmalloc(strlen(buf)+1);
1280 strcpy(sdps_envfrom,buf);
1283 /* Wrap address with To: <> so nxtaddr() likes it */
1284 sdps_envto = xmalloc(strlen(buf)+7);
1285 sprintf(sdps_envto,"To: <%s>",buf);
1289 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1293 #endif /* SDPS_ENABLE */
1296 * Though the POP RFCs don't document this fact, on almost every
1297 * POP3 server I know of messages are marked "seen" only at the
1298 * time the OK response to a RETR is issued.
1300 * This means we can use TOP to fetch the message without setting its
1301 * seen flag. This is good! It means that if the protocol exchange
1302 * craps out during the message, it will still be marked `unseen' on
1303 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1304 * reported to mark messages seen on a TOP fetch.)
1306 * However...*don't* do this if we're using keep to suppress deletion!
1307 * In that case, marking the seen flag is the only way to prevent the
1308 * message from being re-fetched on subsequent runs.
1310 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1311 * This gives us a workaround for servers like usa.net's that bungle
1312 * TOP. It's pretty harmless because fetchall guarantees that any
1313 * message dropped by an interrupted RETR will be picked up on the
1314 * next poll of the site.
1316 * We take advantage here of the fact that, according to all the
1317 * POP RFCs, "if the number of lines requested by the POP3 client
1318 * is greater than than the number of lines in the body, then the
1319 * POP3 server sends the entire message.").
1321 * The line count passed (99999999) is the maximum value CompuServe will
1322 * accept; it's much lower than the natural value 2147483646 (the maximum
1323 * twos-complement signed 32-bit integer minus 1) */
1325 gen_send(sock, "RETR %d", number);
1327 gen_send(sock, "TOP %d 99999999", number);
1328 if ((ok = pop3_ok(sock, buf)) != 0)
1331 *lenp = -1; /* we got sizes from the LIST response */
1336 static void mark_uid_seen(struct query *ctl, int number)
1337 /* Tell the UID code we've seen this. */
1341 if ((sdp = id_find(&ctl->newsaved, number)))
1342 sdp->val.status.mark = UID_SEEN;
1343 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1344 * (say, due to socket error), the same mail will not be downloaded
1347 if ((sdp = id_find(&ctl->oldsaved, number)))
1348 sdp->val.status.mark = UID_SEEN;
1351 static int pop3_delete(int sock, struct query *ctl, int number)
1352 /* delete a given message */
1355 mark_uid_seen(ctl, number);
1356 /* actually, mark for deletion -- doesn't happen until QUIT time */
1357 ok = gen_transact(sock, "DELE %d", number);
1358 if (ok != PS_SUCCESS)
1360 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1364 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1365 /* mark a given message as seen */
1368 mark_uid_seen(ctl, number);
1372 static int pop3_logout(int sock, struct query *ctl)
1373 /* send logout command */
1379 * We used to do this in case the server marks messages deleted when seen.
1380 * (Yes, this has been reported, in the MercuryP/NLM server.
1381 * It's even legal under RFC 1939 (section 8) as a site policy.)
1382 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1383 * "Running 'fetchmail -F -v' and checking the logs, I found out
1384 * that fetchmail did in fact flush my mailbox properly, but sent
1385 * a RSET just before sending QUIT to log off. This caused the
1386 * POP3 server to undo/forget about the previous DELEs, resetting
1387 * my mailbox to its original (ie. unflushed) state. The
1388 * ~/.fetchids file did get flushed though, so the next time
1389 * fetchmail was run it saw all the old messages as new ones ..."
1392 gen_transact(sock, "RSET");
1393 #endif /* __UNUSED__ */
1395 ok = gen_transact(sock, "QUIT");
1402 static const struct method pop3 =
1404 "POP3", /* Post Office Protocol v3 */
1405 "pop3", /* port for plain and TLS POP3 */
1406 "pop3s", /* port for SSL POP3 */
1407 FALSE, /* this is not a tagged protocol */
1408 TRUE, /* this uses a message delimiter */
1409 pop3_ok, /* parse command response */
1410 pop3_getauth, /* get authorization */
1411 pop3_getrange, /* query range of messages */
1412 pop3_getsizes, /* we can get a list of sizes */
1413 pop3_getpartialsizes, /* we can get the size of 1 mail */
1414 pop3_is_old, /* how do we tell a message is old? */
1415 pop3_fetch, /* request given message */
1416 NULL, /* no way to fetch body alone */
1417 NULL, /* no message trailer */
1418 pop3_delete, /* how to delete a message */
1419 pop3_mark_seen, /* how to mark a message as seen */
1420 NULL, /* no action at end of mailbox */
1421 pop3_logout, /* log out, we're done */
1422 FALSE, /* no, we can't re-poll */
1425 int doPOP3 (struct query *ctl)
1426 /* retrieve messages using POP3 */
1429 if (ctl->mailboxes->id) {
1430 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1435 return(do_protocol(ctl, &pop3));
1437 #endif /* POP3_ENABLE */
1439 /* pop3.c ends here */