2 * pop3.c -- POP3 protocol methods
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
17 #include "fetchmail.h"
30 #endif /* OPIE_ENABLE */
32 /* global variables: please reinitialize them explicitly for proper
33 * working in daemon mode */
35 /* TODO: session variables to be initialized before server greeting */
37 static char lastok[POPBUFSIZE+1];
38 #endif /* OPIE_ENABLE */
40 /* session variables initialized in capa_probe() or pop3_getauth() */
41 flag done_capa = FALSE;
43 flag has_gssapi = FALSE;
44 #endif /* defined(GSSAPI) */
45 #if defined(KERBEROS_V5)
46 flag has_kerberos = FALSE;
47 #endif /* defined(KERBEROS_V5) */
48 static flag has_cram = FALSE;
51 #endif /* OPIE_ENABLE */
53 flag has_ntlm = FALSE;
54 #endif /* NTLM_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_V5)
206 has_kerberos = FALSE;
207 #endif /* defined(KERBEROS_V5) */
211 #endif /* OPIE_ENABLE */
214 #endif /* NTLM_ENABLE */
216 ok = gen_transact(sock, "CAPA");
217 if (ok == PS_SUCCESS)
221 /* determine what authentication methods we have available */
222 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
228 if (strstr(buffer, "STLS"))
230 #endif /* SSL_ENABLE */
233 if (strstr(buffer, "GSSAPI"))
235 #endif /* defined(GSSAPI) */
238 if (strstr(buffer, "X-OTP"))
240 #endif /* OPIE_ENABLE */
243 if (strstr(buffer, "NTLM"))
245 #endif /* NTLM_ENABLE */
247 if (strstr(buffer, "CRAM-MD5"))
255 static void set_peek_capable(struct query *ctl)
257 /* we're peek-capable means that the use of TOP is enabled,
258 * see pop3_fetch for details - short story, we can use TOP if
259 * we have a means of reliably tracking which mail we need to
260 * refetch should the connection abort in the middle.
261 * fetchall forces RETR, as does keep without UIDL */
262 peek_capable = !ctl->fetchall;
265 static int do_apop(int sock, struct query *ctl, char *greeting)
269 /* build MD5 digest from greeting timestamp + password */
270 /* find start of timestamp */
271 start = strchr(greeting, '<');
273 if (ctl->server.authenticate == A_APOP || outlevel >= O_DEBUG) {
274 report(ctl->server.authenticate == A_APOP ? stderr : stdout,
275 GT_("Required APOP timestamp not found in greeting\n"));
280 /* find end of timestamp */
281 end = strchr(start + 1, '>');
283 if (!end || end == start + 1) {
285 GT_("Timestamp syntax error in greeting\n"));
291 /* SECURITY: 2007-03-17
292 * Strictly validating the presented challenge for RFC-822
293 * conformity (it must be a msg-id in terms of that standard) is
294 * supposed to make attacks against the MD5 implementation
297 * [1] "Security vulnerability in APOP authentication",
298 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
299 if (!rfc822_valid_msgid((unsigned char *)start)) {
301 GT_("Invalid APOP timestamp.\n"));
305 /* copy timestamp and password into digestion buffer */
306 char *msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
308 strcat(msg,ctl->password);
309 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
312 return gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
315 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
316 /* apply for connection authorization */
321 #endif /* OPIE_ENABLE */
323 flag connection_may_have_tls_errors = FALSE;
324 #endif /* SSL_ENABLE */
329 #endif /* defined(GSSAPI) */
330 #if defined(KERBEROS_V5)
331 has_kerberos = FALSE;
332 #endif /* defined(KERBEROS_V5) */
336 #endif /* OPIE_ENABLE */
339 #endif /* SSL_ENABLE */
341 /* Set this up before authentication quits early. */
342 set_peek_capable(ctl);
344 /* Hack: allow user to force RETR. */
345 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
350 * The "Maillennium POP3/PROXY server" deliberately truncates
351 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
352 * disable TOP. Comcast once spewed marketing babble to the extent
353 * of protecting Outlook -- pretty overzealous to break a protocol
354 * for that that Microsoft could have read, too. Comcast aren't
355 * alone in using this software though.
356 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
357 * (Thanks to Ed Wilts for reminding me of that.)
359 * The warning is printed once per server, until fetchmail exits.
360 * It will be suppressed when --fetchall or other circumstances make
361 * us use RETR anyhow.
365 if (peek_capable && strstr(greeting, "Maillennium POP3")) {
366 if ((ctl->server.workarounds & WKA_TOP) == 0) {
367 report(stdout, GT_("Warning: \"Maillennium POP3\" found, using RETR command instead of TOP.\n"));
368 ctl->server.workarounds |= WKA_TOP;
372 if (ctl->server.authenticate == A_SSH) {
378 * This needs to catch both demon.co.uk and demon.net.
379 * If we see either, and we're in multidrop mode, try to use
380 * the SDPS *ENV extension.
382 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
383 ctl->server.sdps = TRUE;
384 #endif /* SDPS_ENABLE */
386 /* this is a leftover from the times 6.3.X and older when APOP was a
387 * "protocol" (P_APOP) rather than an authenticator (A_APOP),
388 * however, the switch is still useful because we can break; after
389 * an authenticator failed. */
390 switch (ctl->server.protocol) {
393 /* XXX FIXME: AUTH probing (RFC1734) should become global */
394 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
395 if (strstr(ctl->remotename, "@compuserve.com"))
397 /* AUTH command should return a list of available mechanisms */
398 if (gen_transact(sock, "AUTH") == 0)
401 flag has_rpa = FALSE;
403 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
407 if (strncasecmp(buffer, "rpa", 3) == 0)
410 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
411 ctl->password, sock))
417 #endif /* RPA_ENABLE */
420 * CAPA command may return a list including available
421 * authentication mechanisms and STLS capability.
423 * If it doesn't, no harm done, we just fall back to a plain
424 * login -- if the user allows it.
426 * Note that this code latches the server's authentication type,
427 * so that in daemon mode the CAPA check only needs to be done
428 * once at start of run.
430 * If CAPA fails, then force the authentication method to
431 * PASSWORD, switch off opportunistic and repoll immediately.
432 * If TLS is mandatory, fail up front.
434 if ((ctl->server.authenticate == A_ANY) ||
435 (ctl->server.authenticate == A_GSSAPI) ||
436 (ctl->server.authenticate == A_KERBEROS_V5) ||
437 (ctl->server.authenticate == A_OTP) ||
438 (ctl->server.authenticate == A_CRAM_MD5) ||
441 if ((ok = capa_probe(sock)) != PS_SUCCESS)
442 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
443 if (ok == PS_AUTHFAIL ||
444 /* Some servers directly close the socket. However, if we
445 * have already authenticated before, then a previous CAPA
446 * must have succeeded. In that case, treat this as a
447 * genuine socket error and do not change the auth method.
449 (ok == PS_SOCKET && !ctl->wehaveauthed))
453 /* fail with mandatory STLS without repoll */
454 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
455 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
457 } else if (maybe_tls(ctl)) {
458 /* defeat opportunistic STLS */
459 xfree(ctl->sslproto);
460 ctl->sslproto = xstrdup("");
463 /* If strong authentication was opportunistic, retry without, else fail. */
464 switch (ctl->server.authenticate) {
466 ctl->server.authenticate = A_PASSWORD;
468 case A_PASSWORD: /* this should only happen with TLS enabled */
477 if (maybe_tls(ctl)) {
480 commonname = ctl->server.pollname;
482 commonname = ctl->server.via;
483 if (ctl->sslcommonname)
484 commonname = ctl->sslcommonname;
487 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
489 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
490 * protocol that will work with STARTTLS. Don't need to worry
491 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
493 if (gen_transact(sock, "STLS") == PS_SUCCESS
494 && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
495 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
496 ctl->server.pollname, &ctl->remotename)) != -1)
499 * RFC 2595 says this:
501 * "Once TLS has been started, the client MUST discard cached
502 * information about server capabilities and SHOULD re-issue the
503 * CAPABILITY command. This is necessary to protect against
504 * man-in-the-middle attacks which alter the capabilities list prior
505 * to STARTTLS. The server MAY advertise different capabilities
508 * Now that we're confident in our TLS connection we can
509 * guarantee a secure capability re-probe.
513 ok = capa_probe(sock);
514 if (ok != PS_SUCCESS) {
517 if (outlevel >= O_VERBOSE)
519 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
521 } else if (must_tls(ctl)) {
522 /* Config required TLS but we couldn't guarantee it, so we must
525 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
528 /* We don't know whether the connection is usable, and there's
529 * no command we can reasonably issue to test it (NOOP isn't
530 * allowed til post-authentication), so leave it in an unknown
531 * state, mark it as such, and check more carefully if things
532 * go wrong when we try to authenticate. */
534 connection_may_have_tls_errors = TRUE;
535 if (outlevel >= O_VERBOSE)
537 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
542 #endif /* SSL_ENABLE */
545 * OK, we have an authentication type now.
550 (ctl->server.authenticate == A_GSSAPI ||
551 (ctl->server.authenticate == A_ANY
552 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
554 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
555 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
558 #endif /* defined(GSSAPI) */
562 (ctl->server.authenticate == A_OTP ||
563 ctl->server.authenticate == A_ANY))
565 ok = do_otp(sock, "AUTH", ctl);
566 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
569 #endif /* OPIE_ENABLE */
572 /* MSN servers require the use of NTLM (MSN) authentication */
573 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
574 ctl->server.authenticate == A_MSN)
575 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
576 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
577 ok = do_pop3_ntlm(sock, ctl, 0);
578 if (ok == 0 || ctl->server.authenticate != A_ANY)
582 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
585 GT_("Required NTLM capability not compiled into fetchmail\n"));
589 if (ctl->server.authenticate == A_CRAM_MD5 ||
590 (has_cram && ctl->server.authenticate == A_ANY))
592 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
593 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
597 if (ctl->server.authenticate == A_APOP
598 || ctl->server.authenticate == A_ANY)
600 ok = do_apop(sock, ctl, greeting);
601 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
605 /* ordinary validation, no one-time password or RPA */
606 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
610 /* see RFC1938: A One-Time Password System */
611 if ((challenge = strstr(lastok, "otp-"))) {
612 char response[OPIE_RESPONSE_MAX+1];
614 char *n = xstrdup("");
616 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
618 if ((i == -2) && !run.poll_interval) {
619 char secret[OPIE_SECRET_MAX+1];
620 fprintf(stderr, GT_("Secret pass phrase: "));
621 if (opiereadpass(secret, sizeof(secret), 0))
622 i = opiegenerator(challenge, secret, response);
623 memset(secret, 0, sizeof(secret));
631 ok = gen_transact(sock, "PASS %s", response);
634 #endif /* OPIE_ENABLE */
636 /* KPOP uses out-of-band authentication and does not check what
637 * we send here, so send some random fixed string, to avoid
638 * users switching *to* KPOP accidentally revealing their
640 if ((ctl->server.authenticate == A_ANY
641 || ctl->server.authenticate == A_KERBEROS_V5)
642 && (ctl->server.service != NULL
643 && strcmp(ctl->server.service, KPOP_PORT) == 0))
645 ok = gen_transact(sock, "PASS krb_ticket");
649 /* check if we are actually allowed to send the password */
650 if (ctl->server.authenticate == A_ANY
651 || ctl->server.authenticate == A_PASSWORD) {
652 strlcpy(shroud, ctl->password, sizeof(shroud));
653 ok = gen_transact(sock, "PASS %s", ctl->password);
655 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
658 memset(shroud, 0x55, sizeof(shroud));
663 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
668 /* this is for servers which claim to support TLS, but actually
670 if (connection_may_have_tls_errors
671 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
673 xfree(ctl->sslproto);
674 ctl->sslproto = xstrdup("");
675 /* repoll immediately without TLS */
682 /* maybe we detected a lock-busy condition? */
683 if (ok == PS_LOCKBUSY)
684 report(stderr, GT_("lock busy! Is another session active?\n"));
693 /* cut off C string at first POSIX space */
694 static void trim(char *s) {
695 s += strcspn(s, POSIX_space);
699 /** Parse the UID response (leading +OK must have been
700 * stripped off) in buf, store the number in gotnum, and store the ID
701 * into the caller-provided buffer "id" of size "idsize".
702 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
703 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
708 /* skip leading blanks ourselves */
710 i += strspn(i, POSIX_space);
712 *gotnum = strtoul(i, &j, 10);
713 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
714 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
717 j += strspn(j, POSIX_space);
718 strlcpy(id, j, idsize);
723 /** request UIDL for single message \a num and stuff the result into the
724 * buffer \a id which can hold \a idsize bytes */
725 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
728 char buf [POPBUFSIZE+1];
729 unsigned long gotnum;
731 gen_send(sock, "UIDL %d", num);
732 if ((ok = pop3_ok(sock, buf)) != 0)
734 if ((ok = parseuid(buf, &gotnum, id, idsize)))
736 if (gotnum != (unsigned long)num) {
737 report(stderr, GT_("Server responded with UID for wrong message.\n"));
743 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
746 unsigned int first_nr, last_nr, try_nr;
751 while (first_nr < last_nr - 1)
753 struct uid_db_record *rec;
755 try_nr = (first_nr + last_nr) / 2;
756 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
758 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
760 flag mark = rec->status;
761 if (mark == UID_DELETED || mark == UID_EXPUNGED)
763 if (outlevel >= O_VERBOSE)
764 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
765 /* just mark it as seen now! */
766 rec->status = mark = UID_SEEN;
769 /* narrow the search region! */
770 if (mark == UID_UNSEEN)
772 if (outlevel >= O_DEBUG)
773 report(stdout, GT_("%u is unseen\n"), try_nr);
779 /* save the number */
780 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
784 if (outlevel >= O_DEBUG)
785 report(stdout, GT_("%u is unseen\n"), try_nr);
789 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
790 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
793 if (outlevel >= O_DEBUG && last_nr <= count)
794 report(stdout, GT_("%u is first unseen\n"), last_nr);
797 *newp = count - first_nr;
802 static int pop3_getrange(int sock,
805 int *countp, int *newp, int *bytes)
806 /* get range of messages to be fetched */
809 char buf [POPBUFSIZE+1];
812 /* Ensure that the new list is properly empty */
813 clear_uid_db(&ctl->newsaved);
816 /* Alain Knaff suggests this, but it's not RFC standard */
818 if ((ok = gen_transact(sock, "MBOX %s", folder)))
822 /* get the total message count */
823 gen_send(sock, "STAT");
824 ok = pop3_ok(sock, buf);
828 asgn = sscanf(buf,"%d %d", countp, bytes);
834 /* unless fetching all mail, get UID list (UIDL) */
842 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
843 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
845 /* should we do fast uidl this time? */
846 fastuidl = ctl->fastuidl;
847 if (*countp > 7 && /* linear search is better if there are few mails! */
848 !ctl->fetchall && /* with fetchall, all uids are required */
849 !ctl->flush && /* with flush, it is safer to disable fastuidl */
850 NUM_NONZERO (fastuidl))
855 dofastuidl = ctl->fastuidlcount != 0;
863 return(pop3_fastuidl( sock, ctl, *countp, newp));
864 /* grab the mailbox's UID list */
865 if (gen_transact(sock, "UIDL") != 0)
867 if (!ctl->fetchall) {
868 report(stderr, GT_("protocol error while fetching UIDLs\n"));
874 /* UIDL worked - parse reply */
878 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
883 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
885 struct uid_db_record *old_rec, *new_rec;
887 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
889 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
891 flag mark = old_rec->status;
892 if (mark == UID_DELETED || mark == UID_EXPUNGED)
894 /* XXX FIXME: switch 3 occurrences from
895 * (int)unum or (unsigned int)unum to
896 * remove the cast and use %lu - not now
897 * though, time for new release */
898 if (outlevel >= O_VERBOSE)
899 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
900 /* just mark it as seen now! */
901 old_rec->status = mark = UID_SEEN;
903 new_rec->status = mark;
904 if (mark == UID_UNSEEN)
907 if (outlevel >= O_DEBUG)
908 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
914 if (outlevel >= O_DEBUG)
915 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
916 /* add it to oldsaved also! In case, we do not
917 * swap the lists (say, due to socket error),
918 * the same mail will not be downloaded again.
920 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
924 * save the number if it will be needed later on
925 * (messsage will either be fetched or deleted)
927 if (new_rec->status == UID_UNSEEN || ctl->flush) {
928 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
929 set_uid_db_num(&ctl->newsaved, new_rec, unum);
933 } /* multi-line loop for UIDL reply */
941 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
942 /* capture the size of message #first */
945 char buf [POPBUFSIZE+1];
948 for (i = first; i <= last; i++) {
949 gen_send(sock, "LIST %d", i);
950 if ((ok = pop3_ok(sock, buf)) != 0)
952 if (sscanf(buf, "%d %u", &num, &size) == 2) {
954 sizes[i - first] = size;
956 /* warn about possible attempt to induce buffer overrun
958 * we expect server reply message number and requested
959 * message number to match */
960 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
966 static int pop3_getsizes(int sock, int count, int *sizes)
967 /* capture the sizes of all messages */
971 if ((ok = gen_transact(sock, "LIST")) != 0)
975 char buf [POPBUFSIZE+1];
977 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
979 unsigned int num, size;
983 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
984 if (num > 0 && num <= (unsigned)count)
985 sizes[num - 1] = size;
987 /* warn about possible attempt to induce buffer overrun */
988 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
996 static int pop3_is_old(int sock, struct query *ctl, int num)
997 /* is the given message old? */
999 struct uid_db_record *rec;
1001 if (!uid_db_n_records(&ctl->oldsaved))
1002 return (num <= last);
1003 else if (dofastuidl)
1010 /* in fast uidl, we manipulate the old list only! */
1011 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1013 /* we already have the id! */
1014 return(rec->status != UID_UNSEEN);
1017 /* get the uidl first! */
1018 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1021 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1022 /* we already have the id! */
1023 set_uid_db_num(&ctl->oldsaved, rec, num);
1024 return(rec->status != UID_UNSEEN);
1028 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1029 set_uid_db_num(&ctl->oldsaved, rec, num);
1033 rec = find_uid_by_num(&ctl->newsaved, num);
1034 return !rec || rec->status != UID_UNSEEN;
1038 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1039 /* request nth message */
1042 char buf[POPBUFSIZE+1];
1046 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1047 * for a description of what we're parsing here.
1048 * -- updated 2006-02-22
1050 if (ctl->server.sdps)
1054 sdps_envfrom = (char *)NULL;
1055 sdps_envto = (char *)NULL;
1056 gen_send(sock, "*ENV %d", number);
1058 if (gen_recv(sock, buf, sizeof(buf)))
1063 switch (linecount) {
1065 /* No need to wrap envelope from address */
1066 /* FIXME: some parts of fetchmail don't handle null
1067 * envelope senders, so use <> to mark null sender
1068 * as a workaround. */
1069 if (strspn(buf, " \t") == strlen(buf))
1071 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1072 strcpy(sdps_envfrom,buf);
1075 /* Wrap address with To: <> so nxtaddr() likes it */
1076 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1077 sprintf(sdps_envto,"To: <%s>",buf);
1081 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1085 #endif /* SDPS_ENABLE */
1088 * Though the POP RFCs don't document this fact, on almost every
1089 * POP3 server I know of messages are marked "seen" only at the
1090 * time the OK response to a RETR is issued.
1092 * This means we can use TOP to fetch the message without setting its
1093 * seen flag. This is good! It means that if the protocol exchange
1094 * craps out during the message, it will still be marked `unseen' on
1095 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1096 * reported to mark messages seen on a TOP fetch.)
1098 * However...*don't* do this if we're using keep to suppress deletion!
1099 * In that case, marking the seen flag is the only way to prevent the
1100 * message from being re-fetched on subsequent runs.
1102 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1103 * This gives us a workaround for servers like usa.net's that bungle
1104 * TOP. It's pretty harmless because fetchall guarantees that any
1105 * message dropped by an interrupted RETR will be picked up on the
1106 * next poll of the site.
1108 * We take advantage here of the fact that, according to all the
1109 * POP RFCs, "if the number of lines requested by the POP3 client
1110 * is greater than than the number of lines in the body, then the
1111 * POP3 server sends the entire message.").
1113 * The line count passed (99999999) is the maximum value CompuServe will
1114 * accept; it's much lower than the natural value 2147483646 (the maximum
1115 * twos-complement signed 32-bit integer minus 1) */
1117 gen_send(sock, "RETR %d", number);
1119 gen_send(sock, "TOP %d 99999999", number);
1120 if ((ok = pop3_ok(sock, buf)) != 0)
1123 *lenp = -1; /* we got sizes from the LIST response */
1128 static void mark_uid_seen(struct query *ctl, int number)
1129 /* Tell the UID code we've seen this. */
1131 struct uid_db_record *rec;
1133 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1134 rec->status = UID_SEEN;
1135 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1136 * (say, due to socket error), the same mail will not be downloaded
1139 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1140 rec->status = UID_SEEN;
1143 static int pop3_delete(int sock, struct query *ctl, int number)
1144 /* delete a given message */
1146 struct uid_db_record *rec;
1148 mark_uid_seen(ctl, number);
1149 /* actually, mark for deletion -- doesn't happen until QUIT time */
1150 ok = gen_transact(sock, "DELE %d", number);
1151 if (ok != PS_SUCCESS)
1154 rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1155 rec->status = UID_DELETED;
1159 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1160 /* mark a given message as seen */
1163 mark_uid_seen(ctl, number);
1167 static int pop3_logout(int sock, struct query *ctl)
1168 /* send logout command */
1172 ok = gen_transact(sock, "QUIT");
1179 static const struct method pop3 =
1181 "POP3", /* Post Office Protocol v3 */
1182 "pop3", /* port for plain and TLS POP3 */
1183 "pop3s", /* port for SSL POP3 */
1184 FALSE, /* this is not a tagged protocol */
1185 TRUE, /* this uses a message delimiter */
1186 pop3_ok, /* parse command response */
1187 pop3_getauth, /* get authorization */
1188 pop3_getrange, /* query range of messages */
1189 pop3_getsizes, /* we can get a list of sizes */
1190 pop3_getpartialsizes, /* we can get the size of 1 mail */
1191 pop3_is_old, /* how do we tell a message is old? */
1192 pop3_fetch, /* request given message */
1193 NULL, /* no way to fetch body alone */
1194 NULL, /* no message trailer */
1195 pop3_delete, /* how to delete a message */
1196 pop3_mark_seen, /* how to mark a message as seen */
1197 NULL, /* no action at end of mailbox */
1198 pop3_logout, /* log out, we're done */
1199 FALSE, /* no, we can't re-poll */
1202 int doPOP3 (struct query *ctl)
1203 /* retrieve messages using POP3 */
1206 if (ctl->mailboxes->id) {
1207 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1212 return(do_protocol(ctl, &pop3));
1214 #endif /* POP3_ENABLE */
1216 /* pop3.c ends here */