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 char msgbuf[POPBUFSIZE+1];
88 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
90 if ((result = ntlm_helper(sock, ctl, "POP3")))
93 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
96 if (strstr (msgbuf, "OK"))
104 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
106 static int pop3_ok (int sock, char *argbuf)
107 /* parse command response */
110 char buf [POPBUFSIZE+1];
113 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
115 if (*bufp == '+' || *bufp == '-')
120 while (isalpha((unsigned char)*bufp))
126 if (strcmp(buf,"+OK") == 0)
129 strcpy(lastok, bufp);
130 #endif /* OPIE_ENABLE */
133 else if (strncmp(buf,"-ERR", 4) == 0)
135 if (stage == STAGE_FETCH)
137 else if (stage > STAGE_GETAUTH)
140 * We're checking for "lock busy", "unable to lock",
141 * "already locked", "wait a few minutes" etc. here.
142 * This indicates that we have to wait for the server to
143 * unwedge itself before we can poll again.
145 * PS_LOCKBUSY check empirically verified with two recent
146 * versions of the Berkeley popper; QPOP (version 2.2) and
147 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
148 * These are caught by the case-indifferent "lock" check.
149 * The "wait" catches "mail storage services unavailable,
150 * wait a few minutes and try again" on the InterMail server.
152 * If these aren't picked up on correctly, fetchmail will
153 * think there is an authentication failure and wedge the
154 * connection in order to prevent futile polls.
158 else if (strstr(bufp,"lock")
159 || strstr(bufp,"Lock")
160 || strstr(bufp,"LOCK")
161 || strstr(bufp,"wait")
162 /* these are blessed by RFC 2449 */
163 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
165 else if ((strstr(bufp,"Service")
166 || strstr(bufp,"service"))
167 && (strstr(bufp,"unavailable")))
172 * We always want to pass the user lock-busy messages, because
173 * they're red flags. Other stuff (like AUTH failures on non-
174 * RFC1734 servers) only if we're debugging.
176 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
177 report(stderr, "%s\n", bufp);
182 #if POPBUFSIZE > MSGBUFSIZE
183 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
194 static int capa_probe(int sock)
195 /* probe the capabilities of the remote server */
204 #endif /* defined(GSSAPI) */
205 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
206 has_kerberos = FALSE;
207 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
211 #endif /* OPIE_ENABLE */
213 ok = gen_transact(sock, "CAPA");
214 if (ok == PS_SUCCESS)
218 /* determine what authentication methods we have available */
219 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
224 if (strstr(buffer, "STLS"))
226 #endif /* SSL_ENABLE */
228 if (strstr(buffer, "GSSAPI"))
230 #endif /* defined(GSSAPI) */
231 #if defined(KERBEROS_V4)
232 if (strstr(buffer, "KERBEROS_V4"))
234 #endif /* defined(KERBEROS_V4) */
236 if (strstr(buffer, "X-OTP"))
238 #endif /* OPIE_ENABLE */
239 if (strstr(buffer, "CRAM-MD5"))
247 static void set_peek_capable(struct query *ctl)
249 /* we're peek-capable means that the use of TOP is enabled,
250 * see pop3_fetch for details - short story, we can use TOP if
251 * we have a means of reliably tracking which mail we need to
252 * refetch should the connection abort in the middle.
253 * fetchall forces RETR, as does keep without UIDL */
254 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
257 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
258 /* apply for connection authorization */
265 #endif /* OPIE_ENABLE */
267 flag connection_may_have_tls_errors = FALSE;
268 flag got_tls = FALSE;
269 #endif /* SSL_ENABLE */
274 #endif /* defined(GSSAPI) */
275 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
276 has_kerberos = FALSE;
277 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
281 #endif /* OPIE_ENABLE */
284 #endif /* SSL_ENABLE */
286 /* Set this up before authentication quits early. */
287 set_peek_capable(ctl);
289 /* Hack: allow user to force RETR. */
290 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
295 * The "Maillennium POP3/PROXY server" deliberately truncates
296 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
297 * disable TOP. Comcast once spewed marketing babble to the extent
298 * of protecting Outlook -- pretty overzealous to break a protocol
299 * for that that Microsoft could have read, too. Comcast aren't
300 * alone in using this software though.
301 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
302 * (Thanks to Ed Wilts for reminding me of that.)
304 * The warning is printed once per server, until fetchmail exits.
305 * It will be suppressed when --fetchall or other circumstances make
306 * us use RETR anyhow.
310 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
311 if ((ctl->server.workarounds & WKA_TOP) == 0) {
312 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
313 ctl->server.workarounds |= WKA_TOP;
317 if (ctl->server.authenticate == A_SSH) {
323 * This needs to catch both demon.co.uk and demon.net.
324 * If we see either, and we're in multidrop mode, try to use
325 * the SDPS *ENV extension.
327 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
328 ctl->server.sdps = TRUE;
329 #endif /* SDPS_ENABLE */
332 /* MSN servers require the use of NTLM (MSN) authentication */
333 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
334 ctl->server.authenticate == A_MSN)
335 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
336 if (ctl->server.authenticate == A_NTLM)
337 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
339 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
342 GT_("Required NTLM capability not compiled into fetchmail\n"));
346 switch (ctl->server.protocol) {
349 /* XXX FIXME: AUTH probing (RFC1734) should become global */
350 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
351 if (strstr(ctl->remotename, "@compuserve.com"))
353 /* AUTH command should return a list of available mechanisms */
354 if (gen_transact(sock, "AUTH") == 0)
357 flag has_rpa = FALSE;
359 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
363 if (strncasecmp(buffer, "rpa", 3) == 0)
366 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
367 ctl->password, sock))
373 #endif /* RPA_ENABLE */
376 * CAPA command may return a list including available
377 * authentication mechanisms and STLS capability.
379 * If it doesn't, no harm done, we just fall back to a plain
380 * login -- if the user allows it.
382 * Note that this code latches the server's authentication type,
383 * so that in daemon mode the CAPA check only needs to be done
384 * once at start of run.
386 * If CAPA fails, then force the authentication method to
387 * PASSWORD, switch off opportunistic and repoll immediately.
388 * If TLS is mandatory, fail up front.
390 if ((ctl->server.authenticate == A_ANY) ||
391 (ctl->server.authenticate == A_GSSAPI) ||
392 (ctl->server.authenticate == A_KERBEROS_V4) ||
393 (ctl->server.authenticate == A_KERBEROS_V5) ||
394 (ctl->server.authenticate == A_OTP) ||
395 (ctl->server.authenticate == A_CRAM_MD5) ||
398 if ((ok = capa_probe(sock)) != PS_SUCCESS)
399 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
400 if (ok == PS_AUTHFAIL ||
401 /* Some servers directly close the socket. However, if we
402 * have already authenticated before, then a previous CAPA
403 * must have succeeded. In that case, treat this as a
404 * genuine socket error and do not change the auth method.
406 (ok == PS_SOCKET && !ctl->wehaveauthed))
410 /* fail with mandatory STLS without repoll */
411 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
412 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
414 } else if (maybe_tls(ctl)) {
415 /* defeat opportunistic STLS */
416 xfree(ctl->sslproto);
417 ctl->sslproto = xstrdup("");
420 /* If strong authentication was opportunistic, retry without, else fail. */
421 switch (ctl->server.authenticate) {
423 ctl->server.authenticate = A_PASSWORD;
425 case A_PASSWORD: /* this should only happen with TLS enabled */
434 if (maybe_tls(ctl)) {
437 commonname = ctl->server.pollname;
439 commonname = ctl->server.via;
440 if (ctl->sslcommonname)
441 commonname = ctl->sslcommonname;
445 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
446 * protocol that will work with STARTTLS. Don't need to worry
447 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
449 if (gen_transact(sock, "STLS") == PS_SUCCESS
450 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
451 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
452 ctl->server.pollname, &ctl->remotename) != -1)
455 * RFC 2595 says this:
457 * "Once TLS has been started, the client MUST discard cached
458 * information about server capabilities and SHOULD re-issue the
459 * CAPABILITY command. This is necessary to protect against
460 * man-in-the-middle attacks which alter the capabilities list prior
461 * to STARTTLS. The server MAY advertise different capabilities
464 * Now that we're confident in our TLS connection we can
465 * guarantee a secure capability re-probe.
469 ok = capa_probe(sock);
470 if (ok != PS_SUCCESS) {
473 if (outlevel >= O_VERBOSE)
475 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
482 /* Config required TLS but we couldn't guarantee it, so we must
484 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
487 /* We don't know whether the connection is usable, and there's
488 * no command we can reasonably issue to test it (NOOP isn't
489 * allowed til post-authentication), so leave it in an unknown
490 * state, mark it as such, and check more carefully if things
491 * go wrong when we try to authenticate. */
492 connection_may_have_tls_errors = TRUE;
493 if (outlevel >= O_VERBOSE)
495 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
500 #endif /* SSL_ENABLE */
503 * OK, we have an authentication type now.
505 #if defined(KERBEROS_V4)
507 * Servers doing KPOP have to go through a dummy login sequence
508 * rather than doing SASL.
511 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
512 && (ctl->server.authenticate == A_KERBEROS_V4
513 || ctl->server.authenticate == A_KERBEROS_V5
514 || ctl->server.authenticate == A_ANY))
516 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
517 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
520 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
524 (ctl->server.authenticate == A_GSSAPI ||
525 (ctl->server.authenticate == A_ANY
526 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
528 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
529 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
532 #endif /* defined(GSSAPI) */
536 (ctl->server.authenticate == A_OTP ||
537 ctl->server.authenticate == A_ANY))
539 ok = do_otp(sock, "AUTH", ctl);
540 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
543 #endif /* OPIE_ENABLE */
545 if (ctl->server.authenticate == A_CRAM_MD5 ||
546 (has_cram && ctl->server.authenticate == A_ANY))
548 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
549 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
553 /* ordinary validation, no one-time password or RPA */
554 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
558 /* see RFC1938: A One-Time Password System */
559 if ((challenge = strstr(lastok, "otp-"))) {
560 char response[OPIE_RESPONSE_MAX+1];
562 char *n = xstrdup("");
564 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
566 if ((i == -2) && !run.poll_interval) {
567 char secret[OPIE_SECRET_MAX+1];
568 fprintf(stderr, GT_("Secret pass phrase: "));
569 if (opiereadpass(secret, sizeof(secret), 0))
570 i = opiegenerator(challenge, secret, response);
571 memset(secret, 0, sizeof(secret));
579 ok = gen_transact(sock, "PASS %s", response);
582 #endif /* OPIE_ENABLE */
584 /* KPOP uses out-of-band authentication and does not check what
585 * we send here, so send some random fixed string, to avoid
586 * users switching *to* KPOP accidentally revealing their
588 if ((ctl->server.authenticate == A_ANY
589 || ctl->server.authenticate == A_KERBEROS_V4
590 || ctl->server.authenticate == A_KERBEROS_V5)
591 && (ctl->server.service != NULL
592 && strcmp(ctl->server.service, KPOP_PORT) == 0))
594 ok = gen_transact(sock, "PASS krb_ticket");
598 /* check if we are actually allowed to send the password */
599 if (ctl->server.authenticate == A_ANY
600 || ctl->server.authenticate == A_PASSWORD) {
601 strlcpy(shroud, ctl->password, sizeof(shroud));
602 ok = gen_transact(sock, "PASS %s", ctl->password);
604 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
607 memset(shroud, 0x55, sizeof(shroud));
612 /* build MD5 digest from greeting timestamp + password */
613 /* find start of timestamp */
614 for (start = greeting; *start != 0 && *start != '<'; start++)
618 GT_("Required APOP timestamp not found in greeting\n"));
622 /* find end of timestamp */
623 for (end = start; *end != 0 && *end != '>'; end++)
625 if (*end == 0 || end == start + 1) {
627 GT_("Timestamp syntax error in greeting\n"));
633 /* SECURITY: 2007-03-17
634 * Strictly validating the presented challenge for RFC-822
635 * conformity (it must be a msg-id in terms of that standard) is
636 * supposed to make attacks against the MD5 implementation
639 * [1] "Security vulnerability in APOP authentication",
640 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
641 if (!rfc822_valid_msgid((unsigned char *)start)) {
643 GT_("Invalid APOP timestamp.\n"));
647 /* copy timestamp and password into digestion buffer */
648 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
650 strcat(msg,ctl->password);
651 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
654 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
658 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
659 strlcpy(shroud, ctl->password, sizeof(shroud));
660 ok = gen_transact(sock, "RPOP %s", ctl->password);
661 memset(shroud, 0x55, sizeof(shroud));
667 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
672 /* this is for servers which claim to support TLS, but actually
674 if (connection_may_have_tls_errors
675 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
677 xfree(ctl->sslproto);
678 ctl->sslproto = xstrdup("");
679 /* repoll immediately without TLS */
686 /* maybe we detected a lock-busy condition? */
687 if (ok == PS_LOCKBUSY)
688 report(stderr, GT_("lock busy! Is another session active?\n"));
693 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
694 * accepted by Matthias Andree.
696 * Rationale: the server must have locked the spool before returning +OK;
697 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
700 * Empirical experience shows some server/OS combinations
701 * may need a brief pause even after any lockfiles on the
702 * server are released, to give the server time to finish
703 * copying back very large mailfolders from the temp-file...
704 * this is only ever an issue with extremely large mailboxes.
706 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
713 /* cut off C string at first POSIX space */
714 static void trim(char *s) {
715 s += strcspn(s, POSIX_space);
719 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
720 * broken messages) do not have Message-ID headers, and messages without
721 * those appear to break this code and cause fetchmail (at least version
722 * 6.2.3) to not delete such messages properly after retrieval.
723 * See Sourceforge Bug #780933.
725 * The other problem is that the TOP command itself is optional, too... */
726 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
730 char buf [POPBUFSIZE+1];
731 snprintf(buf, sizeof(buf), "TOP %d 1", num);
732 if ((ok = gen_transact(sock, "%s", buf)) != 0)
735 while (gen_recv(sock, buf, sizeof(buf)) == 0)
739 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
742 p += strspn(p, POSIX_space);
743 strlcpy(id, p, idsize);
747 /* XXX FIXME: do not return success here if no Message-ID header was
752 /** Parse the UID response (leading +OK must have been
753 * stripped off) in buf, store the number in gotnum, and store the ID
754 * into the caller-provided buffer "id" of size "idsize".
755 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
756 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
761 /* skip leading blanks ourselves */
763 i += strspn(i, POSIX_space);
765 *gotnum = strtoul(i, &j, 10);
766 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
767 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
770 j += strspn(j, POSIX_space);
771 strlcpy(id, j, idsize);
776 /** request UIDL for single message \a num and stuff the result into the
777 * buffer \a id which can hold \a idsize bytes */
778 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
781 char buf [POPBUFSIZE+1];
782 unsigned long gotnum;
784 gen_send(sock, "UIDL %d", num);
785 if ((ok = pop3_ok(sock, buf)) != 0)
787 if ((ok = parseuid(buf, &gotnum, id, idsize)))
789 if (gotnum != (unsigned long)num) {
790 report(stderr, GT_("Server responded with UID for wrong message.\n"));
796 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
799 unsigned int first_nr, last_nr, try_nr;
804 while (first_nr < last_nr - 1)
808 try_nr = (first_nr + last_nr) / 2;
809 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
811 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
813 flag mark = newl->val.status.mark;
814 if (mark == UID_DELETED || mark == UID_EXPUNGED)
816 if (outlevel >= O_VERBOSE)
817 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
818 /* just mark it as seen now! */
819 newl->val.status.mark = mark = UID_SEEN;
822 /* narrow the search region! */
823 if (mark == UID_UNSEEN)
825 if (outlevel >= O_DEBUG)
826 report(stdout, GT_("%u is unseen\n"), try_nr);
832 /* save the number */
833 newl->val.status.num = try_nr;
837 if (outlevel >= O_DEBUG)
838 report(stdout, GT_("%u is unseen\n"), try_nr);
842 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
843 newl->val.status.num = try_nr;
846 if (outlevel >= O_DEBUG && last_nr <= count)
847 report(stdout, GT_("%u is first unseen\n"), last_nr);
850 *newp = count - first_nr;
855 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
857 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
858 * message will arrive twice with the same Message-ID, so this
859 * slowuidl code will break. Same goes for messages without
860 * Message-ID headers at all. This code would best be removed. */
861 /* This approach tries to get the message headers from the
862 * remote hosts and compares the message-id to the already known
864 * + if the first message containes a new id, all messages on
865 * the server will be new
866 * + if the first is known, try to estimate the last known message
867 * on the server and check. If this works you know the total number
868 * of messages to get.
869 * + Otherwise run a binary search to determine the last known message
871 int ok, nolinear = 0;
872 int first_nr, list_len, try_id, try_nr, add_id;
876 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
879 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
880 /* the first message is unknown -> all messages are new */
885 /* check where we expect the latest known message */
886 list_len = count_list( &ctl->oldsaved );
887 try_id = list_len - first_nr; /* -1 + 1 */
889 if( try_id <= *countp ) {
890 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
893 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
898 if( try_nr != list_len -1 ) {
899 /* some messages inbetween have been deleted... */
903 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
905 for( ; add_id; add_id >>= 1 ) {
907 if( try_id - add_id <= 1 ) {
914 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
916 try_nr = str_nr_in_list(&ctl->oldsaved, id);
923 GT_("Messages inserted into list on server. Cannot handle this.\n"));
928 /* the first try_id messages are known -> copy them to the newsaved list */
929 for( num = first_nr; num < list_len; num++ )
931 struct idlist *newl = save_str(&ctl->newsaved,
932 str_from_nr_list(&ctl->oldsaved, num),
934 newl->val.status.num = num - first_nr + 1;
938 free_str_list(&ctl->oldsaved);
943 *newp = *countp - try_id;
947 static int pop3_getrange(int sock,
950 int *countp, int *newp, int *bytes)
951 /* get range of messages to be fetched */
954 char buf [POPBUFSIZE+1];
957 /* Ensure that the new list is properly empty */
958 ctl->newsaved = (struct idlist *)NULL;
961 /* Alain Knaff suggests this, but it's not RFC standard */
963 if ((ok = gen_transact(sock, "MBOX %s", folder)))
967 /* get the total message count */
968 gen_send(sock, "STAT");
969 ok = pop3_ok(sock, buf);
973 asgn = sscanf(buf,"%d %d", countp, bytes);
980 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
981 * command. We work as hard as possible to hide this, but it makes
982 * counting new messages intrinsically quadratic in the worst case.
986 /* if there are messages, and UIDL is desired, use UIDL
987 * also use UIDL if fetchall is unset */
988 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
993 /* should we do fast uidl this time? */
994 fastuidl = ctl->fastuidl;
995 if (*countp > 7 && /* linear search is better if there are few mails! */
996 !ctl->fetchall && /* with fetchall, all uids are required */
997 !ctl->flush && /* with flush, it is safer to disable fastuidl */
998 NUM_NONZERO (fastuidl))
1003 dofastuidl = ctl->fastuidlcount != 0;
1008 if (!ctl->server.uidl) {
1009 gen_send(sock, "LAST");
1010 ok = pop3_ok(sock, buf);
1016 /* scan LAST reply */
1017 if (sscanf(buf, "%d", &last) == 0)
1019 report(stderr, GT_("protocol error\n"));
1022 *newp = (*countp - last);
1028 return(pop3_fastuidl( sock, ctl, *countp, newp));
1029 /* grab the mailbox's UID list */
1030 if (gen_transact(sock, "UIDL") != 0)
1032 /* don't worry, yet! do it the slow way */
1033 if (pop3_slowuidl(sock, ctl, countp, newp))
1035 report(stderr, GT_("protocol error while fetching UIDLs\n"));
1041 /* UIDL worked - parse reply */
1045 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
1050 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1052 struct idlist *old, *newl;
1054 newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
1055 newl->val.status.num = unum;
1057 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
1059 flag mark = old->val.status.mark;
1060 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1062 /* XXX FIXME: switch 3 occurrences from
1063 * (int)unum or (unsigned int)unum to
1064 * remove the cast and use %lu - not now
1065 * though, time for new release */
1066 if (outlevel >= O_VERBOSE)
1067 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1068 /* just mark it as seen now! */
1069 old->val.status.mark = mark = UID_SEEN;
1071 newl->val.status.mark = mark;
1072 if (mark == UID_UNSEEN)
1075 if (outlevel >= O_DEBUG)
1076 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1082 if (outlevel >= O_DEBUG)
1083 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1084 /* add it to oldsaved also! In case, we do not
1085 * swap the lists (say, due to socket error),
1086 * the same mail will not be downloaded again.
1088 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1090 /* save the number */
1091 old->val.status.num = unum;
1094 } /* multi-line loop for UIDL reply */
1102 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1103 /* capture the size of message #first */
1106 char buf [POPBUFSIZE+1];
1109 for (i = first; i <= last; i++) {
1110 gen_send(sock, "LIST %d", i);
1111 if ((ok = pop3_ok(sock, buf)) != 0)
1113 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1115 sizes[i - first] = size;
1117 /* warn about possible attempt to induce buffer overrun
1119 * we expect server reply message number and requested
1120 * message number to match */
1121 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1127 static int pop3_getsizes(int sock, int count, int *sizes)
1128 /* capture the sizes of all messages */
1132 if ((ok = gen_transact(sock, "LIST")) != 0)
1136 char buf [POPBUFSIZE+1];
1138 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1140 unsigned int num, size;
1144 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1145 if (num > 0 && num <= (unsigned)count)
1146 sizes[num - 1] = size;
1148 /* warn about possible attempt to induce buffer overrun */
1149 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1157 static int pop3_is_old(int sock, struct query *ctl, int num)
1158 /* is the given message old? */
1160 struct idlist *newl;
1162 return (num <= last);
1163 else if (dofastuidl)
1170 /* in fast uidl, we manipulate the old list only! */
1172 if ((newl = id_find(&ctl->oldsaved, num)))
1174 /* we already have the id! */
1175 return(newl->val.status.mark != UID_UNSEEN);
1178 /* get the uidl first! */
1179 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1182 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1183 /* we already have the id! */
1184 newl->val.status.num = num;
1185 return(newl->val.status.mark != UID_UNSEEN);
1189 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1190 newl->val.status.num = num;
1194 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1195 newl->val.status.mark != UID_UNSEEN);
1200 * We could use this to fetch headers only as we do for IMAP. The trouble
1201 * is that there's no way to fetch the body only. So the following RETR
1202 * would have to re-fetch the header. Enough messages have longer headers
1203 * than bodies to make this a net loss.
1205 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1206 /* request headers of nth message */
1209 char buf[POPBUFSIZE+1];
1211 gen_send(sock, "TOP %d 0", number);
1212 if ((ok = pop3_ok(sock, buf)) != 0)
1215 *lenp = -1; /* we got sizes from the LIST response */
1221 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1222 /* request nth message */
1225 char buf[POPBUFSIZE+1];
1229 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1230 * for a description of what we're parsing here.
1231 * -- updated 2006-02-22
1233 if (ctl->server.sdps)
1237 sdps_envfrom = (char *)NULL;
1238 sdps_envto = (char *)NULL;
1239 gen_send(sock, "*ENV %d", number);
1241 if (gen_recv(sock, buf, sizeof(buf)))
1246 switch (linecount) {
1248 /* No need to wrap envelope from address */
1249 /* FIXME: some parts of fetchmail don't handle null
1250 * envelope senders, so use <> to mark null sender
1251 * as a workaround. */
1252 if (strspn(buf, " \t") == strlen(buf))
1254 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1255 strcpy(sdps_envfrom,buf);
1258 /* Wrap address with To: <> so nxtaddr() likes it */
1259 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1260 sprintf(sdps_envto,"To: <%s>",buf);
1264 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1268 #endif /* SDPS_ENABLE */
1271 * Though the POP RFCs don't document this fact, on almost every
1272 * POP3 server I know of messages are marked "seen" only at the
1273 * time the OK response to a RETR is issued.
1275 * This means we can use TOP to fetch the message without setting its
1276 * seen flag. This is good! It means that if the protocol exchange
1277 * craps out during the message, it will still be marked `unseen' on
1278 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1279 * reported to mark messages seen on a TOP fetch.)
1281 * However...*don't* do this if we're using keep to suppress deletion!
1282 * In that case, marking the seen flag is the only way to prevent the
1283 * message from being re-fetched on subsequent runs.
1285 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1286 * This gives us a workaround for servers like usa.net's that bungle
1287 * TOP. It's pretty harmless because fetchall guarantees that any
1288 * message dropped by an interrupted RETR will be picked up on the
1289 * next poll of the site.
1291 * We take advantage here of the fact that, according to all the
1292 * POP RFCs, "if the number of lines requested by the POP3 client
1293 * is greater than than the number of lines in the body, then the
1294 * POP3 server sends the entire message.").
1296 * The line count passed (99999999) is the maximum value CompuServe will
1297 * accept; it's much lower than the natural value 2147483646 (the maximum
1298 * twos-complement signed 32-bit integer minus 1) */
1300 gen_send(sock, "RETR %d", number);
1302 gen_send(sock, "TOP %d 99999999", number);
1303 if ((ok = pop3_ok(sock, buf)) != 0)
1306 *lenp = -1; /* we got sizes from the LIST response */
1311 static void mark_uid_seen(struct query *ctl, int number)
1312 /* Tell the UID code we've seen this. */
1316 if ((sdp = id_find(&ctl->newsaved, number)))
1317 sdp->val.status.mark = UID_SEEN;
1318 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1319 * (say, due to socket error), the same mail will not be downloaded
1322 if ((sdp = id_find(&ctl->oldsaved, number)))
1323 sdp->val.status.mark = UID_SEEN;
1326 static int pop3_delete(int sock, struct query *ctl, int number)
1327 /* delete a given message */
1330 mark_uid_seen(ctl, number);
1331 /* actually, mark for deletion -- doesn't happen until QUIT time */
1332 ok = gen_transact(sock, "DELE %d", number);
1333 if (ok != PS_SUCCESS)
1335 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1339 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1340 /* mark a given message as seen */
1343 mark_uid_seen(ctl, number);
1347 static int pop3_logout(int sock, struct query *ctl)
1348 /* send logout command */
1354 * We used to do this in case the server marks messages deleted when seen.
1355 * (Yes, this has been reported, in the MercuryP/NLM server.
1356 * It's even legal under RFC 1939 (section 8) as a site policy.)
1357 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1358 * "Running 'fetchmail -F -v' and checking the logs, I found out
1359 * that fetchmail did in fact flush my mailbox properly, but sent
1360 * a RSET just before sending QUIT to log off. This caused the
1361 * POP3 server to undo/forget about the previous DELEs, resetting
1362 * my mailbox to its original (ie. unflushed) state. The
1363 * ~/.fetchids file did get flushed though, so the next time
1364 * fetchmail was run it saw all the old messages as new ones ..."
1367 gen_transact(sock, "RSET");
1368 #endif /* __UNUSED__ */
1370 ok = gen_transact(sock, "QUIT");
1377 static const struct method pop3 =
1379 "POP3", /* Post Office Protocol v3 */
1380 "pop3", /* port for plain and TLS POP3 */
1381 "pop3s", /* port for SSL POP3 */
1382 FALSE, /* this is not a tagged protocol */
1383 TRUE, /* this uses a message delimiter */
1384 pop3_ok, /* parse command response */
1385 pop3_getauth, /* get authorization */
1386 pop3_getrange, /* query range of messages */
1387 pop3_getsizes, /* we can get a list of sizes */
1388 pop3_getpartialsizes, /* we can get the size of 1 mail */
1389 pop3_is_old, /* how do we tell a message is old? */
1390 pop3_fetch, /* request given message */
1391 NULL, /* no way to fetch body alone */
1392 NULL, /* no message trailer */
1393 pop3_delete, /* how to delete a message */
1394 pop3_mark_seen, /* how to mark a message as seen */
1395 NULL, /* no action at end of mailbox */
1396 pop3_logout, /* log out, we're done */
1397 FALSE, /* no, we can't re-poll */
1400 int doPOP3 (struct query *ctl)
1401 /* retrieve messages using POP3 */
1404 if (ctl->mailboxes->id) {
1405 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1410 return(do_protocol(ctl, &pop3));
1412 #endif /* POP3_ENABLE */
1414 /* pop3.c ends here */