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"
34 #endif /* OPIE_ENABLE */
36 /* global variables: please reinitialize them explicitly for proper
37 * working in daemon mode */
39 /* TODO: session variables to be initialized before server greeting */
41 static char lastok[POPBUFSIZE+1];
42 #endif /* OPIE_ENABLE */
44 /* session variables initialized in capa_probe() or pop3_getauth() */
45 flag done_capa = FALSE;
47 flag has_gssapi = FALSE;
48 #endif /* defined(GSSAPI) */
49 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
50 flag has_kerberos = FALSE;
51 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
52 static flag has_cram = FALSE;
55 #endif /* OPIE_ENABLE */
57 flag has_ntlm = FALSE;
58 #endif /* NTLM_ENABLE */
60 static flag has_stls = FALSE;
61 #endif /* SSL_ENABLE */
63 /* mailbox variables initialized in pop3_getrange() */
66 /* mail variables initialized in pop3_fetch() */
70 #endif /* SDPS_ENABLE */
76 * NTLM support by Grant Edwards.
78 * Handle MS-Exchange NTLM authentication method. This is the same
79 * as the NTLM auth used by Samba for SMB related services. We just
80 * encode the packets in base64 instead of sending them out via a
83 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
86 static int do_pop3_ntlm(int sock, struct query *ctl,
87 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
89 char msgbuf[POPBUFSIZE+1];
92 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
94 if ((result = ntlm_helper(sock, ctl, "POP3")))
97 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
100 if (strstr (msgbuf, "OK"))
108 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
110 static int pop3_ok (int sock, char *argbuf)
111 /* parse command response */
114 char buf [POPBUFSIZE+1];
117 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
119 if (*bufp == '+' || *bufp == '-')
124 while (isalpha((unsigned char)*bufp))
130 if (strcmp(buf,"+OK") == 0)
133 strcpy(lastok, bufp);
134 #endif /* OPIE_ENABLE */
137 else if (strncmp(buf,"-ERR", 4) == 0)
139 if (stage == STAGE_FETCH)
141 else if (stage > STAGE_GETAUTH)
144 * We're checking for "lock busy", "unable to lock",
145 * "already locked", "wait a few minutes" etc. here.
146 * This indicates that we have to wait for the server to
147 * unwedge itself before we can poll again.
149 * PS_LOCKBUSY check empirically verified with two recent
150 * versions of the Berkeley popper; QPOP (version 2.2) and
151 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
152 * These are caught by the case-indifferent "lock" check.
153 * The "wait" catches "mail storage services unavailable,
154 * wait a few minutes and try again" on the InterMail server.
156 * If these aren't picked up on correctly, fetchmail will
157 * think there is an authentication failure and wedge the
158 * connection in order to prevent futile polls.
162 else if (strstr(bufp,"lock")
163 || strstr(bufp,"Lock")
164 || strstr(bufp,"LOCK")
165 || strstr(bufp,"wait")
166 /* these are blessed by RFC 2449 */
167 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
169 else if ((strstr(bufp,"Service")
170 || strstr(bufp,"service"))
171 && (strstr(bufp,"unavailable")))
176 * We always want to pass the user lock-busy messages, because
177 * they're red flags. Other stuff (like AUTH failures on non-
178 * RFC1734 servers) only if we're debugging.
180 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
181 report(stderr, "%s\n", bufp);
186 #if POPBUFSIZE > MSGBUFSIZE
187 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
198 static int capa_probe(int sock)
199 /* probe the capabilities of the remote server */
208 #endif /* defined(GSSAPI) */
209 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
210 has_kerberos = FALSE;
211 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
215 #endif /* OPIE_ENABLE */
218 #endif /* NTLM_ENABLE */
220 ok = gen_transact(sock, "CAPA");
221 if (ok == PS_SUCCESS)
225 /* determine what authentication methods we have available */
226 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
232 if (strstr(buffer, "STLS"))
234 #endif /* SSL_ENABLE */
237 if (strstr(buffer, "GSSAPI"))
239 #endif /* defined(GSSAPI) */
241 #if defined(KERBEROS_V4)
242 if (strstr(buffer, "KERBEROS_V4"))
244 #endif /* defined(KERBEROS_V4) */
247 if (strstr(buffer, "X-OTP"))
249 #endif /* OPIE_ENABLE */
252 if (strstr(buffer, "NTLM"))
254 #endif /* NTLM_ENABLE */
256 if (strstr(buffer, "CRAM-MD5"))
264 static void set_peek_capable(struct query *ctl)
266 /* we're peek-capable means that the use of TOP is enabled,
267 * see pop3_fetch for details - short story, we can use TOP if
268 * we have a means of reliably tracking which mail we need to
269 * refetch should the connection abort in the middle.
270 * fetchall forces RETR, as does keep without UIDL */
271 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
274 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
275 /* apply for connection authorization */
282 #endif /* OPIE_ENABLE */
284 flag connection_may_have_tls_errors = FALSE;
285 #endif /* SSL_ENABLE */
290 #endif /* defined(GSSAPI) */
291 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
292 has_kerberos = FALSE;
293 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
297 #endif /* OPIE_ENABLE */
300 #endif /* SSL_ENABLE */
302 /* Set this up before authentication quits early. */
303 set_peek_capable(ctl);
305 /* Hack: allow user to force RETR. */
306 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
311 * The "Maillennium POP3/PROXY server" deliberately truncates
312 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
313 * disable TOP. Comcast once spewed marketing babble to the extent
314 * of protecting Outlook -- pretty overzealous to break a protocol
315 * for that that Microsoft could have read, too. Comcast aren't
316 * alone in using this software though.
317 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
318 * (Thanks to Ed Wilts for reminding me of that.)
320 * The warning is printed once per server, until fetchmail exits.
321 * It will be suppressed when --fetchall or other circumstances make
322 * us use RETR anyhow.
326 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
327 if ((ctl->server.workarounds & WKA_TOP) == 0) {
328 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
329 ctl->server.workarounds |= WKA_TOP;
333 if (ctl->server.authenticate == A_SSH) {
339 * This needs to catch both demon.co.uk and demon.net.
340 * If we see either, and we're in multidrop mode, try to use
341 * the SDPS *ENV extension.
343 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
344 ctl->server.sdps = TRUE;
345 #endif /* SDPS_ENABLE */
347 switch (ctl->server.protocol) {
350 /* XXX FIXME: AUTH probing (RFC1734) should become global */
351 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
352 if (strstr(ctl->remotename, "@compuserve.com"))
354 /* AUTH command should return a list of available mechanisms */
355 if (gen_transact(sock, "AUTH") == 0)
358 flag has_rpa = FALSE;
360 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
364 if (strncasecmp(buffer, "rpa", 3) == 0)
367 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
368 ctl->password, sock))
374 #endif /* RPA_ENABLE */
377 * CAPA command may return a list including available
378 * authentication mechanisms and STLS capability.
380 * If it doesn't, no harm done, we just fall back to a plain
381 * login -- if the user allows it.
383 * Note that this code latches the server's authentication type,
384 * so that in daemon mode the CAPA check only needs to be done
385 * once at start of run.
387 * If CAPA fails, then force the authentication method to
388 * PASSWORD, switch off opportunistic and repoll immediately.
389 * If TLS is mandatory, fail up front.
391 if ((ctl->server.authenticate == A_ANY) ||
392 (ctl->server.authenticate == A_GSSAPI) ||
393 (ctl->server.authenticate == A_KERBEROS_V4) ||
394 (ctl->server.authenticate == A_KERBEROS_V5) ||
395 (ctl->server.authenticate == A_OTP) ||
396 (ctl->server.authenticate == A_CRAM_MD5) ||
399 if ((ok = capa_probe(sock)) != PS_SUCCESS)
400 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
401 if (ok == PS_AUTHFAIL ||
402 /* Some servers directly close the socket. However, if we
403 * have already authenticated before, then a previous CAPA
404 * must have succeeded. In that case, treat this as a
405 * genuine socket error and do not change the auth method.
407 (ok == PS_SOCKET && !ctl->wehaveauthed))
411 /* fail with mandatory STLS without repoll */
412 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
413 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
415 } else if (maybe_tls(ctl)) {
416 /* defeat opportunistic STLS */
417 xfree(ctl->sslproto);
418 ctl->sslproto = xstrdup("");
421 /* If strong authentication was opportunistic, retry without, else fail. */
422 switch (ctl->server.authenticate) {
424 ctl->server.authenticate = A_PASSWORD;
426 case A_PASSWORD: /* this should only happen with TLS enabled */
435 if (maybe_tls(ctl)) {
438 commonname = ctl->server.pollname;
440 commonname = ctl->server.via;
441 if (ctl->sslcommonname)
442 commonname = ctl->sslcommonname;
445 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
447 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
448 * protocol that will work with STARTTLS. Don't need to worry
449 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
451 if (gen_transact(sock, "STLS") == PS_SUCCESS
452 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
453 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
454 ctl->server.pollname, &ctl->remotename) != -1)
457 * RFC 2595 says this:
459 * "Once TLS has been started, the client MUST discard cached
460 * information about server capabilities and SHOULD re-issue the
461 * CAPABILITY command. This is necessary to protect against
462 * man-in-the-middle attacks which alter the capabilities list prior
463 * to STARTTLS. The server MAY advertise different capabilities
466 * Now that we're confident in our TLS connection we can
467 * guarantee a secure capability re-probe.
470 ok = capa_probe(sock);
471 if (ok != PS_SUCCESS) {
474 if (outlevel >= O_VERBOSE)
476 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
478 } else if (must_tls(ctl)) {
479 /* Config required TLS but we couldn't guarantee it, so we must
481 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
484 /* We don't know whether the connection is usable, and there's
485 * no command we can reasonably issue to test it (NOOP isn't
486 * allowed til post-authentication), so leave it in an unknown
487 * state, mark it as such, and check more carefully if things
488 * go wrong when we try to authenticate. */
489 connection_may_have_tls_errors = TRUE;
490 if (outlevel >= O_VERBOSE)
492 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
497 #endif /* SSL_ENABLE */
500 * OK, we have an authentication type now.
502 #if defined(KERBEROS_V4)
504 * Servers doing KPOP have to go through a dummy login sequence
505 * rather than doing SASL.
508 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
509 && (ctl->server.authenticate == A_KERBEROS_V4
510 || ctl->server.authenticate == A_KERBEROS_V5
511 || ctl->server.authenticate == A_ANY))
513 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
514 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
517 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
521 (ctl->server.authenticate == A_GSSAPI ||
522 (ctl->server.authenticate == A_ANY
523 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
525 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
526 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
529 #endif /* defined(GSSAPI) */
533 (ctl->server.authenticate == A_OTP ||
534 ctl->server.authenticate == A_ANY))
536 ok = do_otp(sock, "AUTH", ctl);
537 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
540 #endif /* OPIE_ENABLE */
543 /* MSN servers require the use of NTLM (MSN) authentication */
544 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
545 ctl->server.authenticate == A_MSN)
546 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
547 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
548 ok = do_pop3_ntlm(sock, ctl, 0);
549 if (ok == 0 || ctl->server.authenticate != A_ANY)
553 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
556 GT_("Required NTLM capability not compiled into fetchmail\n"));
560 if (ctl->server.authenticate == A_CRAM_MD5 ||
561 (has_cram && ctl->server.authenticate == A_ANY))
563 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
564 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
568 /* ordinary validation, no one-time password or RPA */
569 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
573 /* see RFC1938: A One-Time Password System */
574 if ((challenge = strstr(lastok, "otp-"))) {
575 char response[OPIE_RESPONSE_MAX+1];
577 char *n = xstrdup("");
579 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
581 if ((i == -2) && !run.poll_interval) {
582 char secret[OPIE_SECRET_MAX+1];
583 fprintf(stderr, GT_("Secret pass phrase: "));
584 if (opiereadpass(secret, sizeof(secret), 0))
585 i = opiegenerator(challenge, secret, response);
586 memset(secret, 0, sizeof(secret));
594 ok = gen_transact(sock, "PASS %s", response);
597 #endif /* OPIE_ENABLE */
599 /* KPOP uses out-of-band authentication and does not check what
600 * we send here, so send some random fixed string, to avoid
601 * users switching *to* KPOP accidentally revealing their
603 if ((ctl->server.authenticate == A_ANY
604 || ctl->server.authenticate == A_KERBEROS_V4
605 || ctl->server.authenticate == A_KERBEROS_V5)
606 && (ctl->server.service != NULL
607 && strcmp(ctl->server.service, KPOP_PORT) == 0))
609 ok = gen_transact(sock, "PASS krb_ticket");
613 /* check if we are actually allowed to send the password */
614 if (ctl->server.authenticate == A_ANY
615 || ctl->server.authenticate == A_PASSWORD) {
616 strlcpy(shroud, ctl->password, sizeof(shroud));
617 ok = gen_transact(sock, "PASS %s", ctl->password);
619 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
622 memset(shroud, 0x55, sizeof(shroud));
627 /* build MD5 digest from greeting timestamp + password */
628 /* find start of timestamp */
629 for (start = greeting; *start != 0 && *start != '<'; start++)
633 GT_("Required APOP timestamp not found in greeting\n"));
637 /* find end of timestamp */
638 for (end = start; *end != 0 && *end != '>'; end++)
640 if (*end == 0 || end == start + 1) {
642 GT_("Timestamp syntax error in greeting\n"));
648 /* SECURITY: 2007-03-17
649 * Strictly validating the presented challenge for RFC-822
650 * conformity (it must be a msg-id in terms of that standard) is
651 * supposed to make attacks against the MD5 implementation
654 * [1] "Security vulnerability in APOP authentication",
655 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
656 if (!rfc822_valid_msgid((unsigned char *)start)) {
658 GT_("Invalid APOP timestamp.\n"));
662 /* copy timestamp and password into digestion buffer */
663 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
665 strcat(msg,ctl->password);
666 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
669 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
673 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
674 strlcpy(shroud, ctl->password, sizeof(shroud));
675 ok = gen_transact(sock, "RPOP %s", ctl->password);
676 memset(shroud, 0x55, sizeof(shroud));
682 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
687 /* this is for servers which claim to support TLS, but actually
689 if (connection_may_have_tls_errors
690 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
692 xfree(ctl->sslproto);
693 ctl->sslproto = xstrdup("");
694 /* repoll immediately without TLS */
701 /* maybe we detected a lock-busy condition? */
702 if (ok == PS_LOCKBUSY)
703 report(stderr, GT_("lock busy! Is another session active?\n"));
708 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
709 * accepted by Matthias Andree.
711 * Rationale: the server must have locked the spool before returning +OK;
712 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
715 * Empirical experience shows some server/OS combinations
716 * may need a brief pause even after any lockfiles on the
717 * server are released, to give the server time to finish
718 * copying back very large mailfolders from the temp-file...
719 * this is only ever an issue with extremely large mailboxes.
721 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
728 /* cut off C string at first POSIX space */
729 static void trim(char *s) {
730 s += strcspn(s, POSIX_space);
734 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
735 * broken messages) do not have Message-ID headers, and messages without
736 * those appear to break this code and cause fetchmail (at least version
737 * 6.2.3) to not delete such messages properly after retrieval.
738 * See Sourceforge Bug #780933.
740 * The other problem is that the TOP command itself is optional, too... */
741 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
745 char buf [POPBUFSIZE+1];
746 snprintf(buf, sizeof(buf), "TOP %d 1", num);
747 if ((ok = gen_transact(sock, "%s", buf)) != 0)
750 while (gen_recv(sock, buf, sizeof(buf)) == 0)
754 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
757 p += strspn(p, POSIX_space);
758 strlcpy(id, p, idsize);
762 /* XXX FIXME: do not return success here if no Message-ID header was
767 /** Parse the UID response (leading +OK must have been
768 * stripped off) in buf, store the number in gotnum, and store the ID
769 * into the caller-provided buffer "id" of size "idsize".
770 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
771 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
776 /* skip leading blanks ourselves */
778 i += strspn(i, POSIX_space);
780 *gotnum = strtoul(i, &j, 10);
781 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
782 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
785 j += strspn(j, POSIX_space);
786 strlcpy(id, j, idsize);
791 /** request UIDL for single message \a num and stuff the result into the
792 * buffer \a id which can hold \a idsize bytes */
793 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
796 char buf [POPBUFSIZE+1];
797 unsigned long gotnum;
799 gen_send(sock, "UIDL %d", num);
800 if ((ok = pop3_ok(sock, buf)) != 0)
802 if ((ok = parseuid(buf, &gotnum, id, idsize)))
804 if (gotnum != (unsigned long)num) {
805 report(stderr, GT_("Server responded with UID for wrong message.\n"));
811 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
814 unsigned int first_nr, last_nr, try_nr;
819 while (first_nr < last_nr - 1)
821 struct uid_db_record *rec;
823 try_nr = (first_nr + last_nr) / 2;
824 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
826 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
828 flag mark = rec->status;
829 if (mark == UID_DELETED || mark == UID_EXPUNGED)
831 if (outlevel >= O_VERBOSE)
832 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
833 /* just mark it as seen now! */
834 rec->status = mark = UID_SEEN;
837 /* narrow the search region! */
838 if (mark == UID_UNSEEN)
840 if (outlevel >= O_DEBUG)
841 report(stdout, GT_("%u is unseen\n"), try_nr);
847 /* save the number */
848 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
852 if (outlevel >= O_DEBUG)
853 report(stdout, GT_("%u is unseen\n"), try_nr);
857 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
858 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
861 if (outlevel >= O_DEBUG && last_nr <= count)
862 report(stdout, GT_("%u is first unseen\n"), last_nr);
865 *newp = count - first_nr;
870 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
872 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
873 * message will arrive twice with the same Message-ID, so this
874 * slowuidl code will break. Same goes for messages without
875 * Message-ID headers at all. This code would best be removed. */
876 /* This approach tries to get the message headers from the
877 * remote hosts and compares the message-id to the already known
879 * + if the first message containes a new id, all messages on
880 * the server will be new
881 * + if the first is known, try to estimate the last known message
882 * on the server and check. If this works you know the total number
883 * of messages to get.
884 * + Otherwise run a binary search to determine the last known message
886 struct uid_db_record *rec;
887 int ok, nolinear = 0;
888 int first_nr, n_recs, try_id, try_nr, add_id;
892 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
895 rec = first_uid_in_db(&ctl->oldsaved, id);
897 /* the first message is unknown -> all messages are new */
903 /* check where we expect the latest known message */
904 n_recs = uid_db_n_records(&ctl->oldsaved);
905 try_id = n_recs - first_nr; /* -1 + 1 */
907 if( try_id <= *countp ) {
908 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
911 rec = last_uid_in_db(&ctl->oldsaved, id);
912 try_nr = rec ? rec->pos : -1;
917 if( try_nr != n_recs -1 ) {
918 /* some messages inbetween have been deleted... */
922 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
924 for( ; add_id; add_id >>= 1 ) {
926 if( try_id - add_id <= 1 ) {
933 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
936 rec = find_uid_by_id(&ctl->oldsaved, id);
937 try_nr = rec ? rec->pos : -1;
944 GT_("Messages inserted into list on server. Cannot handle this.\n"));
949 /* the first try_id messages are known -> copy them to the newsaved list */
950 for( num = first_nr; num < n_recs; num++ )
952 rec = find_uid_by_pos(&ctl->oldsaved, num);
954 rec = uid_db_insert(&ctl->newsaved, rec->id, rec->status);
955 set_uid_db_num(&ctl->newsaved, rec, num - first_nr + 1);
959 clear_uid_db(&ctl->oldsaved);
963 *newp = *countp - try_id;
967 static int pop3_getrange(int sock,
970 int *countp, int *newp, int *bytes)
971 /* get range of messages to be fetched */
974 char buf [POPBUFSIZE+1];
977 /* Ensure that the new list is properly empty */
978 clear_uid_db(&ctl->newsaved);
981 /* Alain Knaff suggests this, but it's not RFC standard */
983 if ((ok = gen_transact(sock, "MBOX %s", folder)))
987 /* get the total message count */
988 gen_send(sock, "STAT");
989 ok = pop3_ok(sock, buf);
993 asgn = sscanf(buf,"%d %d", countp, bytes);
1000 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
1001 * command. We work as hard as possible to hide this, but it makes
1002 * counting new messages intrinsically quadratic in the worst case.
1006 /* if there are messages, and UIDL is desired, use UIDL
1007 * also use UIDL if fetchall is unset */
1008 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
1013 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
1014 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
1016 /* should we do fast uidl this time? */
1017 fastuidl = ctl->fastuidl;
1018 if (*countp > 7 && /* linear search is better if there are few mails! */
1019 !ctl->fetchall && /* with fetchall, all uids are required */
1020 !ctl->flush && /* with flush, it is safer to disable fastuidl */
1021 NUM_NONZERO (fastuidl))
1026 dofastuidl = ctl->fastuidlcount != 0;
1031 if (!ctl->server.uidl) {
1032 gen_send(sock, "LAST");
1033 ok = pop3_ok(sock, buf);
1039 /* scan LAST reply */
1040 if (sscanf(buf, "%d", &last) == 0)
1042 report(stderr, GT_("protocol error\n"));
1045 *newp = (*countp - last);
1051 return(pop3_fastuidl( sock, ctl, *countp, newp));
1052 /* grab the mailbox's UID list */
1053 if (gen_transact(sock, "UIDL") != 0)
1055 /* don't worry, yet! do it the slow way */
1056 if (pop3_slowuidl(sock, ctl, countp, newp))
1058 report(stderr, GT_("protocol error while fetching UIDLs\n"));
1064 /* UIDL worked - parse reply */
1068 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
1073 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1075 struct uid_db_record *old_rec, *new_rec;
1077 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
1079 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
1081 flag mark = old_rec->status;
1082 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1084 /* XXX FIXME: switch 3 occurrences from
1085 * (int)unum or (unsigned int)unum to
1086 * remove the cast and use %lu - not now
1087 * though, time for new release */
1088 if (outlevel >= O_VERBOSE)
1089 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1090 /* just mark it as seen now! */
1091 old_rec->status = mark = UID_SEEN;
1093 new_rec->status = mark;
1094 if (mark == UID_UNSEEN)
1097 if (outlevel >= O_DEBUG)
1098 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1104 if (outlevel >= O_DEBUG)
1105 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1106 /* add it to oldsaved also! In case, we do not
1107 * swap the lists (say, due to socket error),
1108 * the same mail will not be downloaded again.
1110 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1113 /* save the number */
1114 if (new_rec->status == UID_UNSEEN || !ctl->keep) {
1115 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
1116 set_uid_db_num(&ctl->newsaved, new_rec, unum);
1120 } /* multi-line loop for UIDL reply */
1128 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1129 /* capture the size of message #first */
1132 char buf [POPBUFSIZE+1];
1135 for (i = first; i <= last; i++) {
1136 gen_send(sock, "LIST %d", i);
1137 if ((ok = pop3_ok(sock, buf)) != 0)
1139 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1141 sizes[i - first] = size;
1143 /* warn about possible attempt to induce buffer overrun
1145 * we expect server reply message number and requested
1146 * message number to match */
1147 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1153 static int pop3_getsizes(int sock, int count, int *sizes)
1154 /* capture the sizes of all messages */
1158 if ((ok = gen_transact(sock, "LIST")) != 0)
1162 char buf [POPBUFSIZE+1];
1164 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1166 unsigned int num, size;
1170 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1171 if (num > 0 && num <= (unsigned)count)
1172 sizes[num - 1] = size;
1174 /* warn about possible attempt to induce buffer overrun */
1175 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1183 static int pop3_is_old(int sock, struct query *ctl, int num)
1184 /* is the given message old? */
1186 struct uid_db_record *rec;
1188 if (!uid_db_n_records(&ctl->oldsaved))
1189 return (num <= last);
1190 else if (dofastuidl)
1197 /* in fast uidl, we manipulate the old list only! */
1199 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1201 /* we already have the id! */
1202 return(rec->status != UID_UNSEEN);
1205 /* get the uidl first! */
1206 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1209 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1210 /* we already have the id! */
1211 set_uid_db_num(&ctl->oldsaved, rec, num);
1212 return(rec->status != UID_UNSEEN);
1216 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1217 set_uid_db_num(&ctl->oldsaved, rec, num);
1221 rec = find_uid_by_num(&ctl->newsaved, num);
1222 return !rec || rec->status != UID_UNSEEN;
1228 * We could use this to fetch headers only as we do for IMAP. The trouble
1229 * is that there's no way to fetch the body only. So the following RETR
1230 * would have to re-fetch the header. Enough messages have longer headers
1231 * than bodies to make this a net loss.
1233 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1234 /* request headers of nth message */
1237 char buf[POPBUFSIZE+1];
1239 gen_send(sock, "TOP %d 0", number);
1240 if ((ok = pop3_ok(sock, buf)) != 0)
1243 *lenp = -1; /* we got sizes from the LIST response */
1249 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1250 /* request nth message */
1253 char buf[POPBUFSIZE+1];
1257 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1258 * for a description of what we're parsing here.
1259 * -- updated 2006-02-22
1261 if (ctl->server.sdps)
1265 sdps_envfrom = (char *)NULL;
1266 sdps_envto = (char *)NULL;
1267 gen_send(sock, "*ENV %d", number);
1269 if (gen_recv(sock, buf, sizeof(buf)))
1274 switch (linecount) {
1276 /* No need to wrap envelope from address */
1277 /* FIXME: some parts of fetchmail don't handle null
1278 * envelope senders, so use <> to mark null sender
1279 * as a workaround. */
1280 if (strspn(buf, " \t") == strlen(buf))
1282 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1283 strcpy(sdps_envfrom,buf);
1286 /* Wrap address with To: <> so nxtaddr() likes it */
1287 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1288 sprintf(sdps_envto,"To: <%s>",buf);
1292 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1296 #endif /* SDPS_ENABLE */
1299 * Though the POP RFCs don't document this fact, on almost every
1300 * POP3 server I know of messages are marked "seen" only at the
1301 * time the OK response to a RETR is issued.
1303 * This means we can use TOP to fetch the message without setting its
1304 * seen flag. This is good! It means that if the protocol exchange
1305 * craps out during the message, it will still be marked `unseen' on
1306 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1307 * reported to mark messages seen on a TOP fetch.)
1309 * However...*don't* do this if we're using keep to suppress deletion!
1310 * In that case, marking the seen flag is the only way to prevent the
1311 * message from being re-fetched on subsequent runs.
1313 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1314 * This gives us a workaround for servers like usa.net's that bungle
1315 * TOP. It's pretty harmless because fetchall guarantees that any
1316 * message dropped by an interrupted RETR will be picked up on the
1317 * next poll of the site.
1319 * We take advantage here of the fact that, according to all the
1320 * POP RFCs, "if the number of lines requested by the POP3 client
1321 * is greater than than the number of lines in the body, then the
1322 * POP3 server sends the entire message.").
1324 * The line count passed (99999999) is the maximum value CompuServe will
1325 * accept; it's much lower than the natural value 2147483646 (the maximum
1326 * twos-complement signed 32-bit integer minus 1) */
1328 gen_send(sock, "RETR %d", number);
1330 gen_send(sock, "TOP %d 99999999", number);
1331 if ((ok = pop3_ok(sock, buf)) != 0)
1334 *lenp = -1; /* we got sizes from the LIST response */
1339 static void mark_uid_seen(struct query *ctl, int number)
1340 /* Tell the UID code we've seen this. */
1342 struct uid_db_record *rec;
1344 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1345 rec->status = UID_SEEN;
1346 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1347 * (say, due to socket error), the same mail will not be downloaded
1350 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1351 rec->status = UID_SEEN;
1354 static int pop3_delete(int sock, struct query *ctl, int number)
1355 /* delete a given message */
1357 struct uid_db_record *rec;
1359 mark_uid_seen(ctl, number);
1360 /* actually, mark for deletion -- doesn't happen until QUIT time */
1361 ok = gen_transact(sock, "DELE %d", number);
1362 if (ok != PS_SUCCESS)
1365 rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1366 rec->status = UID_DELETED;
1370 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1371 /* mark a given message as seen */
1374 mark_uid_seen(ctl, number);
1378 static int pop3_logout(int sock, struct query *ctl)
1379 /* send logout command */
1385 * We used to do this in case the server marks messages deleted when seen.
1386 * (Yes, this has been reported, in the MercuryP/NLM server.
1387 * It's even legal under RFC 1939 (section 8) as a site policy.)
1388 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1389 * "Running 'fetchmail -F -v' and checking the logs, I found out
1390 * that fetchmail did in fact flush my mailbox properly, but sent
1391 * a RSET just before sending QUIT to log off. This caused the
1392 * POP3 server to undo/forget about the previous DELEs, resetting
1393 * my mailbox to its original (ie. unflushed) state. The
1394 * ~/.fetchids file did get flushed though, so the next time
1395 * fetchmail was run it saw all the old messages as new ones ..."
1398 gen_transact(sock, "RSET");
1399 #endif /* __UNUSED__ */
1401 ok = gen_transact(sock, "QUIT");
1408 static const struct method pop3 =
1410 "POP3", /* Post Office Protocol v3 */
1411 "pop3", /* port for plain and TLS POP3 */
1412 "pop3s", /* port for SSL POP3 */
1413 FALSE, /* this is not a tagged protocol */
1414 TRUE, /* this uses a message delimiter */
1415 pop3_ok, /* parse command response */
1416 pop3_getauth, /* get authorization */
1417 pop3_getrange, /* query range of messages */
1418 pop3_getsizes, /* we can get a list of sizes */
1419 pop3_getpartialsizes, /* we can get the size of 1 mail */
1420 pop3_is_old, /* how do we tell a message is old? */
1421 pop3_fetch, /* request given message */
1422 NULL, /* no way to fetch body alone */
1423 NULL, /* no message trailer */
1424 pop3_delete, /* how to delete a message */
1425 pop3_mark_seen, /* how to mark a message as seen */
1426 NULL, /* no action at end of mailbox */
1427 pop3_logout, /* log out, we're done */
1428 FALSE, /* no, we can't re-poll */
1431 int doPOP3 (struct query *ctl)
1432 /* retrieve messages using POP3 */
1435 if (ctl->mailboxes->id) {
1436 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1441 return(do_protocol(ctl, &pop3));
1443 #endif /* POP3_ENABLE */
1445 /* pop3.c ends here */