2 * pop3.c -- POP3 protocol methods
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
14 #if defined(HAVE_UNISTD_H)
17 #if defined(STDC_HEADERS)
22 #include "fetchmail.h"
35 #endif /* OPIE_ENABLE */
37 /* global variables: please reinitialize them explicitly for proper
38 * working in daemon mode */
40 /* TODO: session variables to be initialized before server greeting */
42 static char lastok[POPBUFSIZE+1];
43 #endif /* OPIE_ENABLE */
45 /* session variables initialized in capa_probe() or pop3_getauth() */
46 flag done_capa = FALSE;
48 flag has_gssapi = FALSE;
49 #endif /* defined(GSSAPI) */
50 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
51 flag has_kerberos = FALSE;
52 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
53 static flag has_cram = FALSE;
56 #endif /* OPIE_ENABLE */
58 flag has_ntlm = FALSE;
59 #endif /* NTLM_ENABLE */
61 static flag has_stls = FALSE;
62 #endif /* SSL_ENABLE */
64 /* mailbox variables initialized in pop3_getrange() */
67 /* mail variables initialized in pop3_fetch() */
71 #endif /* SDPS_ENABLE */
77 * NTLM support by Grant Edwards.
79 * Handle MS-Exchange NTLM authentication method. This is the same
80 * as the NTLM auth used by Samba for SMB related services. We just
81 * encode the packets in base64 instead of sending them out via a
84 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
87 static int do_pop3_ntlm(int sock, struct query *ctl,
88 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
90 char msgbuf[POPBUFSIZE+1];
93 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
95 if ((result = ntlm_helper(sock, ctl, "POP3")))
98 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
101 if (strstr (msgbuf, "OK"))
109 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
111 static int pop3_ok (int sock, char *argbuf)
112 /* parse command response */
115 char buf [POPBUFSIZE+1];
118 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
120 if (*bufp == '+' || *bufp == '-')
125 while (isalpha((unsigned char)*bufp))
131 if (strcmp(buf,"+OK") == 0)
134 strcpy(lastok, bufp);
135 #endif /* OPIE_ENABLE */
138 else if (strncmp(buf,"-ERR", 4) == 0)
140 if (stage == STAGE_FETCH)
142 else if (stage > STAGE_GETAUTH)
145 * We're checking for "lock busy", "unable to lock",
146 * "already locked", "wait a few minutes" etc. here.
147 * This indicates that we have to wait for the server to
148 * unwedge itself before we can poll again.
150 * PS_LOCKBUSY check empirically verified with two recent
151 * versions of the Berkeley popper; QPOP (version 2.2) and
152 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
153 * These are caught by the case-indifferent "lock" check.
154 * The "wait" catches "mail storage services unavailable,
155 * wait a few minutes and try again" on the InterMail server.
157 * If these aren't picked up on correctly, fetchmail will
158 * think there is an authentication failure and wedge the
159 * connection in order to prevent futile polls.
163 else if (strstr(bufp,"lock")
164 || strstr(bufp,"Lock")
165 || strstr(bufp,"LOCK")
166 || strstr(bufp,"wait")
167 /* these are blessed by RFC 2449 */
168 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
170 else if ((strstr(bufp,"Service")
171 || strstr(bufp,"service"))
172 && (strstr(bufp,"unavailable")))
177 * We always want to pass the user lock-busy messages, because
178 * they're red flags. Other stuff (like AUTH failures on non-
179 * RFC1734 servers) only if we're debugging.
181 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
182 report(stderr, "%s\n", bufp);
187 #if POPBUFSIZE > MSGBUFSIZE
188 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
199 static int capa_probe(int sock)
200 /* probe the capabilities of the remote server */
209 #endif /* defined(GSSAPI) */
210 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
211 has_kerberos = FALSE;
212 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
216 #endif /* OPIE_ENABLE */
219 #endif /* NTLM_ENABLE */
221 ok = gen_transact(sock, "CAPA");
222 if (ok == PS_SUCCESS)
226 /* determine what authentication methods we have available */
227 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
233 if (strstr(buffer, "STLS"))
235 #endif /* SSL_ENABLE */
238 if (strstr(buffer, "GSSAPI"))
240 #endif /* defined(GSSAPI) */
242 #if defined(KERBEROS_V4)
243 if (strstr(buffer, "KERBEROS_V4"))
245 #endif /* defined(KERBEROS_V4) */
248 if (strstr(buffer, "X-OTP"))
250 #endif /* OPIE_ENABLE */
253 if (strstr(buffer, "NTLM"))
255 #endif /* NTLM_ENABLE */
257 if (strstr(buffer, "CRAM-MD5"))
265 static void set_peek_capable(struct query *ctl)
267 /* we're peek-capable means that the use of TOP is enabled,
268 * see pop3_fetch for details - short story, we can use TOP if
269 * we have a means of reliably tracking which mail we need to
270 * refetch should the connection abort in the middle.
271 * fetchall forces RETR, as does keep without UIDL */
272 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
275 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
276 /* apply for connection authorization */
283 #endif /* OPIE_ENABLE */
285 flag connection_may_have_tls_errors = FALSE;
287 #endif /* SSL_ENABLE */
292 #endif /* defined(GSSAPI) */
293 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
294 has_kerberos = FALSE;
295 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
299 #endif /* OPIE_ENABLE */
302 #endif /* SSL_ENABLE */
304 /* Set this up before authentication quits early. */
305 set_peek_capable(ctl);
307 /* Hack: allow user to force RETR. */
308 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
313 * The "Maillennium POP3/PROXY server" deliberately truncates
314 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
315 * disable TOP. Comcast once spewed marketing babble to the extent
316 * of protecting Outlook -- pretty overzealous to break a protocol
317 * for that that Microsoft could have read, too. Comcast aren't
318 * alone in using this software though.
319 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
320 * (Thanks to Ed Wilts for reminding me of that.)
322 * The warning is printed once per server, until fetchmail exits.
323 * It will be suppressed when --fetchall or other circumstances make
324 * us use RETR anyhow.
328 if (peek_capable && strstr(greeting, "Maillennium POP3")) {
329 if ((ctl->server.workarounds & WKA_TOP) == 0) {
330 report(stdout, GT_("Warning: \"Maillennium POP3\" found, using RETR command instead of TOP.\n"));
331 ctl->server.workarounds |= WKA_TOP;
335 if (ctl->server.authenticate == A_SSH) {
341 * This needs to catch both demon.co.uk and demon.net.
342 * If we see either, and we're in multidrop mode, try to use
343 * the SDPS *ENV extension.
345 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
346 ctl->server.sdps = TRUE;
347 #endif /* SDPS_ENABLE */
349 switch (ctl->server.protocol) {
352 /* XXX FIXME: AUTH probing (RFC1734) should become global */
353 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
354 if (strstr(ctl->remotename, "@compuserve.com"))
356 /* AUTH command should return a list of available mechanisms */
357 if (gen_transact(sock, "AUTH") == 0)
360 flag has_rpa = FALSE;
362 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
366 if (strncasecmp(buffer, "rpa", 3) == 0)
369 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
370 ctl->password, sock))
376 #endif /* RPA_ENABLE */
379 * CAPA command may return a list including available
380 * authentication mechanisms and STLS capability.
382 * If it doesn't, no harm done, we just fall back to a plain
383 * login -- if the user allows it.
385 * Note that this code latches the server's authentication type,
386 * so that in daemon mode the CAPA check only needs to be done
387 * once at start of run.
389 * If CAPA fails, then force the authentication method to
390 * PASSWORD, switch off opportunistic and repoll immediately.
391 * If TLS is mandatory, fail up front.
393 if ((ctl->server.authenticate == A_ANY) ||
394 (ctl->server.authenticate == A_GSSAPI) ||
395 (ctl->server.authenticate == A_KERBEROS_V4) ||
396 (ctl->server.authenticate == A_KERBEROS_V5) ||
397 (ctl->server.authenticate == A_OTP) ||
398 (ctl->server.authenticate == A_CRAM_MD5) ||
401 if ((ok = capa_probe(sock)) != PS_SUCCESS)
402 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
403 if (ok == PS_AUTHFAIL ||
404 /* Some servers directly close the socket. However, if we
405 * have already authenticated before, then a previous CAPA
406 * must have succeeded. In that case, treat this as a
407 * genuine socket error and do not change the auth method.
409 (ok == PS_SOCKET && !ctl->wehaveauthed))
412 if (must_starttls(ctl)) {
413 /* fail with mandatory STLS without repoll */
414 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
415 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
417 } else if (maybe_starttls(ctl)) {
418 /* defeat opportunistic STLS */
419 xfree(ctl->sslproto);
420 ctl->sslproto = xstrdup("");
423 /* If strong authentication was opportunistic, retry without, else fail. */
424 switch (ctl->server.authenticate) {
426 ctl->server.authenticate = A_PASSWORD;
428 case A_PASSWORD: /* this should only happen with TLS enabled */
437 commonname = ctl->server.pollname;
439 commonname = ctl->server.via;
440 if (ctl->sslcommonname)
441 commonname = ctl->sslcommonname;
443 if (maybe_starttls(ctl)) {
444 if (has_stls || must_starttls(ctl)) /* if TLS is mandatory, ignore capabilities */
446 /* Don't need to worry whether TLS is mandatory or
447 * opportunistic unless SSLOpen() fails (see below). */
448 if (gen_transact(sock, "STLS") == PS_SUCCESS
449 && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, ctl->sslproto, ctl->sslcertck,
450 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
451 ctl->server.pollname, &ctl->remotename)) != -1)
454 * RFC 2595 says this:
456 * "Once TLS has been started, the client MUST discard cached
457 * information about server capabilities and SHOULD re-issue the
458 * CAPABILITY command. This is necessary to protect against
459 * man-in-the-middle attacks which alter the capabilities list prior
460 * to STARTTLS. The server MAY advertise different capabilities
463 * Now that we're confident in our TLS connection we can
464 * guarantee a secure capability re-probe.
468 ok = capa_probe(sock);
469 if (ok != PS_SUCCESS) {
472 if (outlevel >= O_VERBOSE)
474 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
476 } else if (must_starttls(ctl)) {
477 /* Config required TLS but we couldn't guarantee it, so we must
480 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
483 /* We don't know whether the connection is usable, and there's
484 * no command we can reasonably issue to test it (NOOP isn't
485 * allowed til post-authentication), so leave it in an unknown
486 * state, mark it as such, and check more carefully if things
487 * 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);
496 } else { /* maybe_starttls() */
497 if (has_stls && outlevel >= O_VERBOSE) {
498 report(stdout, GT_("%s: WARNING: server offered STLS, but sslproto '' given.\n"), commonname);
500 } /* maybe_starttls() */
501 #endif /* SSL_ENABLE */
504 * OK, we have an authentication type now.
506 #if defined(KERBEROS_V4)
508 * Servers doing KPOP have to go through a dummy login sequence
509 * rather than doing SASL.
512 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
513 && (ctl->server.authenticate == A_KERBEROS_V4
514 || ctl->server.authenticate == A_KERBEROS_V5
515 || ctl->server.authenticate == A_ANY))
517 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
518 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
521 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
525 (ctl->server.authenticate == A_GSSAPI ||
526 (ctl->server.authenticate == A_ANY
527 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
529 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
530 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
533 #endif /* defined(GSSAPI) */
537 (ctl->server.authenticate == A_OTP ||
538 ctl->server.authenticate == A_ANY))
540 ok = do_otp(sock, "AUTH", ctl);
541 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
544 #endif /* OPIE_ENABLE */
547 /* MSN servers require the use of NTLM (MSN) authentication */
548 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
549 ctl->server.authenticate == A_MSN)
550 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
551 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
552 ok = do_pop3_ntlm(sock, ctl, 0);
553 if (ok == 0 || ctl->server.authenticate != A_ANY)
557 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
560 GT_("Required NTLM capability not compiled into fetchmail\n"));
564 if (ctl->server.authenticate == A_CRAM_MD5 ||
565 (has_cram && ctl->server.authenticate == A_ANY))
567 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
568 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
572 /* ordinary validation, no one-time password or RPA */
573 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
577 /* see RFC1938: A One-Time Password System */
578 if ((challenge = strstr(lastok, "otp-"))) {
579 char response[OPIE_RESPONSE_MAX+1];
581 char *n = xstrdup("");
583 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
585 if ((i == -2) && !run.poll_interval) {
586 char secret[OPIE_SECRET_MAX+1];
587 fprintf(stderr, GT_("Secret pass phrase: "));
588 if (opiereadpass(secret, sizeof(secret), 0))
589 i = opiegenerator(challenge, secret, response);
590 memset(secret, 0, sizeof(secret));
598 ok = gen_transact(sock, "PASS %s", response);
601 #endif /* OPIE_ENABLE */
603 /* KPOP uses out-of-band authentication and does not check what
604 * we send here, so send some random fixed string, to avoid
605 * users switching *to* KPOP accidentally revealing their
607 if ((ctl->server.authenticate == A_ANY
608 || ctl->server.authenticate == A_KERBEROS_V4
609 || ctl->server.authenticate == A_KERBEROS_V5)
610 && (ctl->server.service != NULL
611 && strcmp(ctl->server.service, KPOP_PORT) == 0))
613 ok = gen_transact(sock, "PASS krb_ticket");
617 /* check if we are actually allowed to send the password */
618 if (ctl->server.authenticate == A_ANY
619 || ctl->server.authenticate == A_PASSWORD) {
620 strlcpy(shroud, ctl->password, sizeof(shroud));
621 ok = gen_transact(sock, "PASS %s", ctl->password);
623 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
626 memset(shroud, 0x55, sizeof(shroud));
631 /* build MD5 digest from greeting timestamp + password */
632 /* find start of timestamp */
633 for (start = greeting; *start != 0 && *start != '<'; start++)
637 GT_("Required APOP timestamp not found in greeting\n"));
641 /* find end of timestamp */
642 for (end = start; *end != 0 && *end != '>'; end++)
644 if (*end == 0 || end == start + 1) {
646 GT_("Timestamp syntax error in greeting\n"));
652 /* SECURITY: 2007-03-17
653 * Strictly validating the presented challenge for RFC-822
654 * conformity (it must be a msg-id in terms of that standard) is
655 * supposed to make attacks against the MD5 implementation
658 * [1] "Security vulnerability in APOP authentication",
659 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
660 if (!rfc822_valid_msgid((unsigned char *)start)) {
662 GT_("Invalid APOP timestamp.\n"));
666 /* copy timestamp and password into digestion buffer */
667 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
669 strcat(msg,ctl->password);
670 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
673 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
677 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
678 strlcpy(shroud, ctl->password, sizeof(shroud));
679 ok = gen_transact(sock, "RPOP %s", ctl->password);
680 memset(shroud, 0x55, sizeof(shroud));
686 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
691 /* this is for servers which claim to support TLS, but actually
693 if (connection_may_have_tls_errors
694 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
696 xfree(ctl->sslproto);
697 ctl->sslproto = xstrdup("");
698 /* repoll immediately without TLS */
705 /* maybe we detected a lock-busy condition? */
706 if (ok == PS_LOCKBUSY)
707 report(stderr, GT_("lock busy! Is another session active?\n"));
716 /* cut off C string at first POSIX space */
717 static void trim(char *s) {
718 s += strcspn(s, POSIX_space);
722 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
723 * broken messages) do not have Message-ID headers, and messages without
724 * those appear to break this code and cause fetchmail (at least version
725 * 6.2.3) to not delete such messages properly after retrieval.
726 * See Sourceforge Bug #780933.
728 * The other problem is that the TOP command itself is optional, too... */
729 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
733 char buf [POPBUFSIZE+1];
734 snprintf(buf, sizeof(buf), "TOP %d 1", num);
735 if ((ok = gen_transact(sock, "%s", buf)) != 0)
738 while (gen_recv(sock, buf, sizeof(buf)) == 0)
742 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
745 p += strspn(p, POSIX_space);
746 strlcpy(id, p, idsize);
750 /* XXX FIXME: do not return success here if no Message-ID header was
755 /** Parse the UID response (leading +OK must have been
756 * stripped off) in buf, store the number in gotnum, and store the ID
757 * into the caller-provided buffer "id" of size "idsize".
758 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
759 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
764 /* skip leading blanks ourselves */
766 i += strspn(i, POSIX_space);
768 *gotnum = strtoul(i, &j, 10);
769 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
770 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
773 j += strspn(j, POSIX_space);
774 strlcpy(id, j, idsize);
779 /** request UIDL for single message \a num and stuff the result into the
780 * buffer \a id which can hold \a idsize bytes */
781 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
784 char buf [POPBUFSIZE+1];
785 unsigned long gotnum;
787 gen_send(sock, "UIDL %d", num);
788 if ((ok = pop3_ok(sock, buf)) != 0)
790 if ((ok = parseuid(buf, &gotnum, id, idsize)))
792 if (gotnum != (unsigned long)num) {
793 report(stderr, GT_("Server responded with UID for wrong message.\n"));
799 /** Do a binary search with single UIDL commands to find the first
801 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
804 unsigned int first_nr, last_nr, try_nr;
809 while (first_nr < last_nr - 1)
811 struct uid_db_record *rec;
813 try_nr = (first_nr + last_nr) / 2;
814 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
816 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
818 flag mark = rec->status;
819 if (mark == UID_DELETED || mark == UID_EXPUNGED)
821 if (outlevel >= O_VERBOSE)
822 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
823 /* just mark it as seen now! */
824 rec->status = mark = UID_SEEN;
827 /* narrow the search region! */
828 if (mark == UID_UNSEEN)
830 if (outlevel >= O_DEBUG)
831 report(stdout, GT_("%u is unseen\n"), try_nr);
837 /* save the number */
838 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
842 if (outlevel >= O_DEBUG)
843 report(stdout, GT_("%u is unseen\n"), try_nr);
847 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
848 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
851 if (outlevel >= O_DEBUG && last_nr <= count)
852 report(stdout, GT_("%u is first unseen\n"), last_nr);
855 *newp = count - first_nr;
860 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
862 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
863 * message will arrive twice with the same Message-ID, so this
864 * slowuidl code will break. Same goes for messages without
865 * Message-ID headers at all. This code would best be removed. */
866 /* This approach tries to get the message headers from the
867 * remote hosts and compares the message-id to the already known
869 * + if the first message containes a new id, all messages on
870 * the server will be new
871 * + if the first is known, try to estimate the last known message
872 * on the server and check. If this works you know the total number
873 * of messages to get.
874 * + Otherwise run a binary search to determine the last known message
876 struct uid_db_record *rec;
877 int ok, nolinear = 0;
878 int first_nr, n_recs, try_id, try_nr, add_id;
882 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
885 rec = first_uid_in_db(&ctl->oldsaved, id);
887 /* the first message is unknown -> all messages are new */
893 /* check where we expect the latest known message */
894 n_recs = uid_db_n_records(&ctl->oldsaved);
895 try_id = n_recs - first_nr; /* -1 + 1 */
897 if( try_id <= *countp ) {
898 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
901 rec = last_uid_in_db(&ctl->oldsaved, id);
902 try_nr = rec ? (int)rec->pos : -1;
907 if( try_nr != n_recs -1 ) {
908 /* some messages inbetween have been deleted... */
912 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
914 for( ; add_id; add_id >>= 1 ) {
916 if( try_id - add_id <= 1 ) {
923 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
926 rec = find_uid_by_id(&ctl->oldsaved, id);
927 try_nr = rec ? (int)rec->pos : -1;
934 GT_("Messages inserted into list on server. Cannot handle this.\n"));
939 /* the first try_id messages are known -> copy them to the newsaved list */
940 for( num = first_nr; num < n_recs; num++ )
942 rec = find_uid_by_pos(&ctl->oldsaved, num);
944 rec = uid_db_insert(&ctl->newsaved, rec->id, rec->status);
945 set_uid_db_num(&ctl->newsaved, rec, num - first_nr + 1);
949 clear_uid_db(&ctl->oldsaved);
953 *newp = *countp - try_id;
957 static int pop3_getrange(int sock,
960 int *countp, int *newp, int *bytes)
961 /* get range of messages to be fetched */
964 char buf [POPBUFSIZE+1];
967 /* Ensure that the new list is properly empty */
968 clear_uid_db(&ctl->newsaved);
971 /* Alain Knaff suggests this, but it's not RFC standard */
973 if ((ok = gen_transact(sock, "MBOX %s", folder)))
977 /* get the total message count */
978 gen_send(sock, "STAT");
979 ok = pop3_ok(sock, buf);
983 asgn = sscanf(buf,"%d %d", countp, bytes);
990 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
991 * command. We work as hard as possible to hide this, but it makes
992 * counting new messages intrinsically quadratic in the worst case.
996 /* if there are messages, and UIDL is desired, use UIDL
997 * also use UIDL if fetchall is unset */
998 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
1003 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
1004 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
1006 /* should we do fast uidl this time? */
1007 fastuidl = ctl->fastuidl;
1008 if (*countp > 7 && /* linear search is better if there are few mails! */
1009 !ctl->fetchall && /* with fetchall, all uids are required */
1010 !ctl->flush && /* with flush, it is safer to disable fastuidl */
1011 NUM_NONZERO (fastuidl))
1016 dofastuidl = ctl->fastuidlcount != 0;
1021 if (!ctl->server.uidl) {
1022 gen_send(sock, "LAST");
1023 ok = pop3_ok(sock, buf);
1029 /* scan LAST reply */
1030 if (sscanf(buf, "%d", &last) == 0)
1032 report(stderr, GT_("protocol error\n"));
1035 *newp = (*countp - last);
1041 return(pop3_fastuidl( sock, ctl, *countp, newp));
1042 /* grab the mailbox's UID list */
1043 if (gen_transact(sock, "UIDL") != 0)
1045 /* don't worry, yet! do it the slow way */
1046 if (pop3_slowuidl(sock, ctl, countp, newp))
1048 report(stderr, GT_("protocol error while fetching UIDLs\n"));
1054 /* UIDL worked - parse reply */
1058 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
1063 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1065 struct uid_db_record *old_rec, *new_rec;
1067 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
1069 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
1071 flag mark = old_rec->status;
1072 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1074 /* XXX FIXME: switch 3 occurrences from
1075 * (int)unum or (unsigned int)unum to
1076 * remove the cast and use %lu - not now
1077 * though, time for new release */
1078 if (outlevel >= O_VERBOSE)
1079 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1080 /* just mark it as seen now! */
1081 old_rec->status = mark = UID_SEEN;
1083 new_rec->status = mark;
1084 if (mark == UID_UNSEEN)
1087 if (outlevel >= O_DEBUG)
1088 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1094 if (outlevel >= O_DEBUG)
1095 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1096 /* add it to oldsaved also! In case, we do not
1097 * swap the lists (say, due to socket error),
1098 * the same mail will not be downloaded again.
1100 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1104 * save the number if it will be needed later on
1105 * (messsage will either be fetched or deleted)
1107 if (new_rec->status == UID_UNSEEN || ctl->flush) {
1108 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
1109 set_uid_db_num(&ctl->newsaved, new_rec, unum);
1113 } /* multi-line loop for UIDL reply */
1121 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1122 /* capture the size of message #first */
1125 char buf [POPBUFSIZE+1];
1128 for (i = first; i <= last; i++) {
1129 gen_send(sock, "LIST %d", i);
1130 if ((ok = pop3_ok(sock, buf)) != 0)
1132 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1134 sizes[i - first] = size;
1136 /* warn about possible attempt to induce buffer overrun
1138 * we expect server reply message number and requested
1139 * message number to match */
1140 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1146 static int pop3_getsizes(int sock, int count, int *sizes)
1147 /* capture the sizes of all messages */
1151 if ((ok = gen_transact(sock, "LIST")) != 0)
1155 char buf [POPBUFSIZE+1];
1157 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1159 unsigned int num, size;
1163 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1164 if (num > 0 && num <= (unsigned)count)
1165 sizes[num - 1] = size;
1167 /* warn about possible attempt to induce buffer overrun */
1168 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1176 static int pop3_is_old(int sock, struct query *ctl, int num)
1177 /* is the given message old? */
1179 struct uid_db_record *rec;
1181 if (!uid_db_n_records(&ctl->oldsaved))
1182 return (num <= last);
1183 else if (dofastuidl)
1190 /* in fast uidl, we manipulate the old list only! */
1192 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1194 /* we already have the id! */
1195 return(rec->status != UID_UNSEEN);
1198 /* get the uidl first! */
1199 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1202 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1203 /* we already have the id! */
1204 set_uid_db_num(&ctl->oldsaved, rec, num);
1205 return(rec->status != UID_UNSEEN);
1209 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1210 set_uid_db_num(&ctl->oldsaved, rec, num);
1214 rec = find_uid_by_num(&ctl->newsaved, num);
1215 return !rec || rec->status != UID_UNSEEN;
1219 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1220 /* request nth message */
1223 char buf[POPBUFSIZE+1];
1227 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1228 * for a description of what we're parsing here.
1229 * -- updated 2006-02-22
1231 if (ctl->server.sdps)
1235 sdps_envfrom = (char *)NULL;
1236 sdps_envto = (char *)NULL;
1237 gen_send(sock, "*ENV %d", number);
1239 if (gen_recv(sock, buf, sizeof(buf)))
1244 switch (linecount) {
1246 /* No need to wrap envelope from address */
1247 /* FIXME: some parts of fetchmail don't handle null
1248 * envelope senders, so use <> to mark null sender
1249 * as a workaround. */
1250 if (strspn(buf, " \t") == strlen(buf))
1252 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1253 strcpy(sdps_envfrom,buf);
1256 /* Wrap address with To: <> so nxtaddr() likes it */
1257 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1258 sprintf(sdps_envto,"To: <%s>",buf);
1262 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1266 #endif /* SDPS_ENABLE */
1269 * Though the POP RFCs don't document this fact, on almost every
1270 * POP3 server I know of messages are marked "seen" only at the
1271 * time the OK response to a RETR is issued.
1273 * This means we can use TOP to fetch the message without setting its
1274 * seen flag. This is good! It means that if the protocol exchange
1275 * craps out during the message, it will still be marked `unseen' on
1276 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1277 * reported to mark messages seen on a TOP fetch.)
1279 * However...*don't* do this if we're using keep to suppress deletion!
1280 * In that case, marking the seen flag is the only way to prevent the
1281 * message from being re-fetched on subsequent runs.
1283 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1284 * This gives us a workaround for servers like usa.net's that bungle
1285 * TOP. It's pretty harmless because fetchall guarantees that any
1286 * message dropped by an interrupted RETR will be picked up on the
1287 * next poll of the site.
1289 * We take advantage here of the fact that, according to all the
1290 * POP RFCs, "if the number of lines requested by the POP3 client
1291 * is greater than than the number of lines in the body, then the
1292 * POP3 server sends the entire message.").
1294 * The line count passed (99999999) is the maximum value CompuServe will
1295 * accept; it's much lower than the natural value 2147483646 (the maximum
1296 * twos-complement signed 32-bit integer minus 1) */
1298 gen_send(sock, "RETR %d", number);
1300 gen_send(sock, "TOP %d 99999999", number);
1301 if ((ok = pop3_ok(sock, buf)) != 0)
1304 *lenp = -1; /* we got sizes from the LIST response */
1309 static void mark_uid_seen(struct query *ctl, int number)
1310 /* Tell the UID code we've seen this. */
1312 struct uid_db_record *rec;
1314 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1315 rec->status = UID_SEEN;
1316 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1317 * (say, due to socket error), the same mail will not be downloaded
1320 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1321 rec->status = UID_SEEN;
1324 static int pop3_delete(int sock, struct query *ctl, int number)
1325 /* delete a given message */
1327 struct uid_db_record *rec;
1329 mark_uid_seen(ctl, number);
1330 /* actually, mark for deletion -- doesn't happen until QUIT time */
1331 ok = gen_transact(sock, "DELE %d", number);
1332 if (ok != PS_SUCCESS)
1335 if ((rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number)))
1336 rec->status = UID_DELETED;
1341 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1342 /* mark a given message as seen */
1345 mark_uid_seen(ctl, number);
1349 static int pop3_logout(int sock, struct query *ctl)
1350 /* send logout command */
1354 ok = gen_transact(sock, "QUIT");
1361 static const struct method pop3 =
1363 "POP3", /* Post Office Protocol v3 */
1364 "pop3", /* port for plain and TLS POP3 */
1365 "pop3s", /* port for SSL POP3 */
1366 FALSE, /* this is not a tagged protocol */
1367 TRUE, /* this uses a message delimiter */
1368 pop3_ok, /* parse command response */
1369 pop3_getauth, /* get authorization */
1370 pop3_getrange, /* query range of messages */
1371 pop3_getsizes, /* we can get a list of sizes */
1372 pop3_getpartialsizes, /* we can get the size of 1 mail */
1373 pop3_is_old, /* how do we tell a message is old? */
1374 pop3_fetch, /* request given message */
1375 NULL, /* no way to fetch body alone */
1376 NULL, /* no message trailer */
1377 pop3_delete, /* how to delete a message */
1378 pop3_mark_seen, /* how to mark a message as seen */
1379 NULL, /* no action at end of mailbox */
1380 pop3_logout, /* log out, we're done */
1381 FALSE, /* no, we can't re-poll */
1384 int doPOP3 (struct query *ctl)
1385 /* retrieve messages using POP3 */
1388 if (ctl->mailboxes->id) {
1389 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1394 return(do_protocol(ctl, &pop3));
1396 #endif /* POP3_ENABLE */
1398 /* pop3.c ends here */