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 pop3_getauth(int sock, struct query *ctl, char *greeting)
266 /* apply for connection authorization */
273 #endif /* OPIE_ENABLE */
275 flag connection_may_have_tls_errors = FALSE;
276 #endif /* SSL_ENABLE */
281 #endif /* defined(GSSAPI) */
282 #if defined(KERBEROS_V5)
283 has_kerberos = FALSE;
284 #endif /* defined(KERBEROS_V5) */
288 #endif /* OPIE_ENABLE */
291 #endif /* SSL_ENABLE */
293 /* Set this up before authentication quits early. */
294 set_peek_capable(ctl);
296 /* Hack: allow user to force RETR. */
297 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
302 * The "Maillennium POP3/PROXY server" deliberately truncates
303 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
304 * disable TOP. Comcast once spewed marketing babble to the extent
305 * of protecting Outlook -- pretty overzealous to break a protocol
306 * for that that Microsoft could have read, too. Comcast aren't
307 * alone in using this software though.
308 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
309 * (Thanks to Ed Wilts for reminding me of that.)
311 * The warning is printed once per server, until fetchmail exits.
312 * It will be suppressed when --fetchall or other circumstances make
313 * us use RETR anyhow.
317 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
318 if ((ctl->server.workarounds & WKA_TOP) == 0) {
319 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
320 ctl->server.workarounds |= WKA_TOP;
324 if (ctl->server.authenticate == A_SSH) {
330 * This needs to catch both demon.co.uk and demon.net.
331 * If we see either, and we're in multidrop mode, try to use
332 * the SDPS *ENV extension.
334 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
335 ctl->server.sdps = TRUE;
336 #endif /* SDPS_ENABLE */
338 switch (ctl->server.protocol) {
341 /* XXX FIXME: AUTH probing (RFC1734) should become global */
342 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
343 if (strstr(ctl->remotename, "@compuserve.com"))
345 /* AUTH command should return a list of available mechanisms */
346 if (gen_transact(sock, "AUTH") == 0)
349 flag has_rpa = FALSE;
351 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
355 if (strncasecmp(buffer, "rpa", 3) == 0)
358 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
359 ctl->password, sock))
365 #endif /* RPA_ENABLE */
368 * CAPA command may return a list including available
369 * authentication mechanisms and STLS capability.
371 * If it doesn't, no harm done, we just fall back to a plain
372 * login -- if the user allows it.
374 * Note that this code latches the server's authentication type,
375 * so that in daemon mode the CAPA check only needs to be done
376 * once at start of run.
378 * If CAPA fails, then force the authentication method to
379 * PASSWORD, switch off opportunistic and repoll immediately.
380 * If TLS is mandatory, fail up front.
382 if ((ctl->server.authenticate == A_ANY) ||
383 (ctl->server.authenticate == A_GSSAPI) ||
384 (ctl->server.authenticate == A_KERBEROS_V5) ||
385 (ctl->server.authenticate == A_OTP) ||
386 (ctl->server.authenticate == A_CRAM_MD5) ||
389 if ((ok = capa_probe(sock)) != PS_SUCCESS)
390 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
391 if (ok == PS_AUTHFAIL ||
392 /* Some servers directly close the socket. However, if we
393 * have already authenticated before, then a previous CAPA
394 * must have succeeded. In that case, treat this as a
395 * genuine socket error and do not change the auth method.
397 (ok == PS_SOCKET && !ctl->wehaveauthed))
401 /* fail with mandatory STLS without repoll */
402 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
403 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
405 } else if (maybe_tls(ctl)) {
406 /* defeat opportunistic STLS */
407 xfree(ctl->sslproto);
408 ctl->sslproto = xstrdup("");
411 /* If strong authentication was opportunistic, retry without, else fail. */
412 switch (ctl->server.authenticate) {
414 ctl->server.authenticate = A_PASSWORD;
416 case A_PASSWORD: /* this should only happen with TLS enabled */
425 if (maybe_tls(ctl)) {
428 commonname = ctl->server.pollname;
430 commonname = ctl->server.via;
431 if (ctl->sslcommonname)
432 commonname = ctl->sslcommonname;
435 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
437 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
438 * protocol that will work with STARTTLS. Don't need to worry
439 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
441 if (gen_transact(sock, "STLS") == PS_SUCCESS
442 && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
443 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
444 ctl->server.pollname, &ctl->remotename)) != -1)
447 * RFC 2595 says this:
449 * "Once TLS has been started, the client MUST discard cached
450 * information about server capabilities and SHOULD re-issue the
451 * CAPABILITY command. This is necessary to protect against
452 * man-in-the-middle attacks which alter the capabilities list prior
453 * to STARTTLS. The server MAY advertise different capabilities
456 * Now that we're confident in our TLS connection we can
457 * guarantee a secure capability re-probe.
461 ok = capa_probe(sock);
462 if (ok != PS_SUCCESS) {
465 if (outlevel >= O_VERBOSE)
467 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
469 } else if (must_tls(ctl)) {
470 /* Config required TLS but we couldn't guarantee it, so we must
473 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
476 /* We don't know whether the connection is usable, and there's
477 * no command we can reasonably issue to test it (NOOP isn't
478 * allowed til post-authentication), so leave it in an unknown
479 * state, mark it as such, and check more carefully if things
480 * go wrong when we try to authenticate. */
482 connection_may_have_tls_errors = TRUE;
483 if (outlevel >= O_VERBOSE)
485 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
490 #endif /* SSL_ENABLE */
493 * OK, we have an authentication type now.
498 (ctl->server.authenticate == A_GSSAPI ||
499 (ctl->server.authenticate == A_ANY
500 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
502 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
503 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
506 #endif /* defined(GSSAPI) */
510 (ctl->server.authenticate == A_OTP ||
511 ctl->server.authenticate == A_ANY))
513 ok = do_otp(sock, "AUTH", ctl);
514 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
517 #endif /* OPIE_ENABLE */
520 /* MSN servers require the use of NTLM (MSN) authentication */
521 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
522 ctl->server.authenticate == A_MSN)
523 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
524 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
525 ok = do_pop3_ntlm(sock, ctl, 0);
526 if (ok == 0 || ctl->server.authenticate != A_ANY)
530 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
533 GT_("Required NTLM capability not compiled into fetchmail\n"));
537 if (ctl->server.authenticate == A_CRAM_MD5 ||
538 (has_cram && ctl->server.authenticate == A_ANY))
540 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
541 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
545 /* ordinary validation, no one-time password or RPA */
546 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
550 /* see RFC1938: A One-Time Password System */
551 if ((challenge = strstr(lastok, "otp-"))) {
552 char response[OPIE_RESPONSE_MAX+1];
554 char *n = xstrdup("");
556 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
558 if ((i == -2) && !run.poll_interval) {
559 char secret[OPIE_SECRET_MAX+1];
560 fprintf(stderr, GT_("Secret pass phrase: "));
561 if (opiereadpass(secret, sizeof(secret), 0))
562 i = opiegenerator(challenge, secret, response);
563 memset(secret, 0, sizeof(secret));
571 ok = gen_transact(sock, "PASS %s", response);
574 #endif /* OPIE_ENABLE */
576 /* KPOP uses out-of-band authentication and does not check what
577 * we send here, so send some random fixed string, to avoid
578 * users switching *to* KPOP accidentally revealing their
580 if ((ctl->server.authenticate == A_ANY
581 || ctl->server.authenticate == A_KERBEROS_V5)
582 && (ctl->server.service != NULL
583 && strcmp(ctl->server.service, KPOP_PORT) == 0))
585 ok = gen_transact(sock, "PASS krb_ticket");
589 /* check if we are actually allowed to send the password */
590 if (ctl->server.authenticate == A_ANY
591 || ctl->server.authenticate == A_PASSWORD) {
592 strlcpy(shroud, ctl->password, sizeof(shroud));
593 ok = gen_transact(sock, "PASS %s", ctl->password);
595 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
598 memset(shroud, 0x55, sizeof(shroud));
603 /* build MD5 digest from greeting timestamp + password */
604 /* find start of timestamp */
605 for (start = greeting; *start != 0 && *start != '<'; start++)
609 GT_("Required APOP timestamp not found in greeting\n"));
613 /* find end of timestamp */
614 for (end = start; *end != 0 && *end != '>'; end++)
616 if (*end == 0 || end == start + 1) {
618 GT_("Timestamp syntax error in greeting\n"));
624 /* SECURITY: 2007-03-17
625 * Strictly validating the presented challenge for RFC-822
626 * conformity (it must be a msg-id in terms of that standard) is
627 * supposed to make attacks against the MD5 implementation
630 * [1] "Security vulnerability in APOP authentication",
631 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
632 if (!rfc822_valid_msgid((unsigned char *)start)) {
634 GT_("Invalid APOP timestamp.\n"));
638 /* copy timestamp and password into digestion buffer */
639 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
641 strcat(msg,ctl->password);
642 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
645 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
649 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
654 /* this is for servers which claim to support TLS, but actually
656 if (connection_may_have_tls_errors
657 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
659 xfree(ctl->sslproto);
660 ctl->sslproto = xstrdup("");
661 /* repoll immediately without TLS */
668 /* maybe we detected a lock-busy condition? */
669 if (ok == PS_LOCKBUSY)
670 report(stderr, GT_("lock busy! Is another session active?\n"));
675 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
676 * accepted by Matthias Andree.
678 * Rationale: the server must have locked the spool before returning +OK;
679 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
682 * Empirical experience shows some server/OS combinations
683 * may need a brief pause even after any lockfiles on the
684 * server are released, to give the server time to finish
685 * copying back very large mailfolders from the temp-file...
686 * this is only ever an issue with extremely large mailboxes.
688 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
695 /* cut off C string at first POSIX space */
696 static void trim(char *s) {
697 s += strcspn(s, POSIX_space);
701 /** Parse the UID response (leading +OK must have been
702 * stripped off) in buf, store the number in gotnum, and store the ID
703 * into the caller-provided buffer "id" of size "idsize".
704 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
705 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
710 /* skip leading blanks ourselves */
712 i += strspn(i, POSIX_space);
714 *gotnum = strtoul(i, &j, 10);
715 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
716 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
719 j += strspn(j, POSIX_space);
720 strlcpy(id, j, idsize);
725 /** request UIDL for single message \a num and stuff the result into the
726 * buffer \a id which can hold \a idsize bytes */
727 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
730 char buf [POPBUFSIZE+1];
731 unsigned long gotnum;
733 gen_send(sock, "UIDL %d", num);
734 if ((ok = pop3_ok(sock, buf)) != 0)
736 if ((ok = parseuid(buf, &gotnum, id, idsize)))
738 if (gotnum != (unsigned long)num) {
739 report(stderr, GT_("Server responded with UID for wrong message.\n"));
745 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
748 unsigned int first_nr, last_nr, try_nr;
753 while (first_nr < last_nr - 1)
755 struct uid_db_record *rec;
757 try_nr = (first_nr + last_nr) / 2;
758 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
760 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
762 flag mark = rec->status;
763 if (mark == UID_DELETED || mark == UID_EXPUNGED)
765 if (outlevel >= O_VERBOSE)
766 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
767 /* just mark it as seen now! */
768 rec->status = mark = UID_SEEN;
771 /* narrow the search region! */
772 if (mark == UID_UNSEEN)
774 if (outlevel >= O_DEBUG)
775 report(stdout, GT_("%u is unseen\n"), try_nr);
781 /* save the number */
782 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
786 if (outlevel >= O_DEBUG)
787 report(stdout, GT_("%u is unseen\n"), try_nr);
791 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
792 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
795 if (outlevel >= O_DEBUG && last_nr <= count)
796 report(stdout, GT_("%u is first unseen\n"), last_nr);
799 *newp = count - first_nr;
804 static int pop3_getrange(int sock,
807 int *countp, int *newp, int *bytes)
808 /* get range of messages to be fetched */
811 char buf [POPBUFSIZE+1];
814 /* Ensure that the new list is properly empty */
815 clear_uid_db(&ctl->newsaved);
818 /* Alain Knaff suggests this, but it's not RFC standard */
820 if ((ok = gen_transact(sock, "MBOX %s", folder)))
824 /* get the total message count */
825 gen_send(sock, "STAT");
826 ok = pop3_ok(sock, buf);
830 asgn = sscanf(buf,"%d %d", countp, bytes);
836 /* unless fetching all mail, get UID list (UIDL) */
844 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
845 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
847 /* should we do fast uidl this time? */
848 fastuidl = ctl->fastuidl;
849 if (*countp > 7 && /* linear search is better if there are few mails! */
850 !ctl->fetchall && /* with fetchall, all uids are required */
851 !ctl->flush && /* with flush, it is safer to disable fastuidl */
852 NUM_NONZERO (fastuidl))
857 dofastuidl = ctl->fastuidlcount != 0;
865 return(pop3_fastuidl( sock, ctl, *countp, newp));
866 /* grab the mailbox's UID list */
867 if (gen_transact(sock, "UIDL") != 0)
869 if (!ctl->fetchall) {
870 report(stderr, GT_("protocol error while fetching UIDLs\n"));
876 /* UIDL worked - parse reply */
880 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
885 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
887 struct uid_db_record *old_rec, *new_rec;
889 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
891 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
893 flag mark = old_rec->status;
894 if (mark == UID_DELETED || mark == UID_EXPUNGED)
896 /* XXX FIXME: switch 3 occurrences from
897 * (int)unum or (unsigned int)unum to
898 * remove the cast and use %lu - not now
899 * though, time for new release */
900 if (outlevel >= O_VERBOSE)
901 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
902 /* just mark it as seen now! */
903 old_rec->status = mark = UID_SEEN;
905 new_rec->status = mark;
906 if (mark == UID_UNSEEN)
909 if (outlevel >= O_DEBUG)
910 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
916 if (outlevel >= O_DEBUG)
917 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
918 /* add it to oldsaved also! In case, we do not
919 * swap the lists (say, due to socket error),
920 * the same mail will not be downloaded again.
922 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
926 * save the number if it will be needed later on
927 * (messsage will either be fetched or deleted)
929 if (new_rec->status == UID_UNSEEN || ctl->flush) {
930 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
931 set_uid_db_num(&ctl->newsaved, new_rec, unum);
935 } /* multi-line loop for UIDL reply */
943 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
944 /* capture the size of message #first */
947 char buf [POPBUFSIZE+1];
950 for (i = first; i <= last; i++) {
951 gen_send(sock, "LIST %d", i);
952 if ((ok = pop3_ok(sock, buf)) != 0)
954 if (sscanf(buf, "%d %u", &num, &size) == 2) {
956 sizes[i - first] = size;
958 /* warn about possible attempt to induce buffer overrun
960 * we expect server reply message number and requested
961 * message number to match */
962 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
968 static int pop3_getsizes(int sock, int count, int *sizes)
969 /* capture the sizes of all messages */
973 if ((ok = gen_transact(sock, "LIST")) != 0)
977 char buf [POPBUFSIZE+1];
979 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
981 unsigned int num, size;
985 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
986 if (num > 0 && num <= (unsigned)count)
987 sizes[num - 1] = size;
989 /* warn about possible attempt to induce buffer overrun */
990 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
998 static int pop3_is_old(int sock, struct query *ctl, int num)
999 /* is the given message old? */
1001 struct uid_db_record *rec;
1003 if (!uid_db_n_records(&ctl->oldsaved))
1004 return (num <= last);
1005 else if (dofastuidl)
1012 /* in fast uidl, we manipulate the old list only! */
1013 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1015 /* we already have the id! */
1016 return(rec->status != UID_UNSEEN);
1019 /* get the uidl first! */
1020 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1023 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1024 /* we already have the id! */
1025 set_uid_db_num(&ctl->oldsaved, rec, num);
1026 return(rec->status != UID_UNSEEN);
1030 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1031 set_uid_db_num(&ctl->oldsaved, rec, num);
1035 rec = find_uid_by_num(&ctl->newsaved, num);
1036 return !rec || rec->status != UID_UNSEEN;
1040 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1041 /* request nth message */
1044 char buf[POPBUFSIZE+1];
1048 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1049 * for a description of what we're parsing here.
1050 * -- updated 2006-02-22
1052 if (ctl->server.sdps)
1056 sdps_envfrom = (char *)NULL;
1057 sdps_envto = (char *)NULL;
1058 gen_send(sock, "*ENV %d", number);
1060 if (gen_recv(sock, buf, sizeof(buf)))
1065 switch (linecount) {
1067 /* No need to wrap envelope from address */
1068 /* FIXME: some parts of fetchmail don't handle null
1069 * envelope senders, so use <> to mark null sender
1070 * as a workaround. */
1071 if (strspn(buf, " \t") == strlen(buf))
1073 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1074 strcpy(sdps_envfrom,buf);
1077 /* Wrap address with To: <> so nxtaddr() likes it */
1078 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1079 sprintf(sdps_envto,"To: <%s>",buf);
1083 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1087 #endif /* SDPS_ENABLE */
1090 * Though the POP RFCs don't document this fact, on almost every
1091 * POP3 server I know of messages are marked "seen" only at the
1092 * time the OK response to a RETR is issued.
1094 * This means we can use TOP to fetch the message without setting its
1095 * seen flag. This is good! It means that if the protocol exchange
1096 * craps out during the message, it will still be marked `unseen' on
1097 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1098 * reported to mark messages seen on a TOP fetch.)
1100 * However...*don't* do this if we're using keep to suppress deletion!
1101 * In that case, marking the seen flag is the only way to prevent the
1102 * message from being re-fetched on subsequent runs.
1104 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1105 * This gives us a workaround for servers like usa.net's that bungle
1106 * TOP. It's pretty harmless because fetchall guarantees that any
1107 * message dropped by an interrupted RETR will be picked up on the
1108 * next poll of the site.
1110 * We take advantage here of the fact that, according to all the
1111 * POP RFCs, "if the number of lines requested by the POP3 client
1112 * is greater than than the number of lines in the body, then the
1113 * POP3 server sends the entire message.").
1115 * The line count passed (99999999) is the maximum value CompuServe will
1116 * accept; it's much lower than the natural value 2147483646 (the maximum
1117 * twos-complement signed 32-bit integer minus 1) */
1119 gen_send(sock, "RETR %d", number);
1121 gen_send(sock, "TOP %d 99999999", number);
1122 if ((ok = pop3_ok(sock, buf)) != 0)
1125 *lenp = -1; /* we got sizes from the LIST response */
1130 static void mark_uid_seen(struct query *ctl, int number)
1131 /* Tell the UID code we've seen this. */
1133 struct uid_db_record *rec;
1135 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1136 rec->status = UID_SEEN;
1137 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1138 * (say, due to socket error), the same mail will not be downloaded
1141 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1142 rec->status = UID_SEEN;
1145 static int pop3_delete(int sock, struct query *ctl, int number)
1146 /* delete a given message */
1148 struct uid_db_record *rec;
1150 mark_uid_seen(ctl, number);
1151 /* actually, mark for deletion -- doesn't happen until QUIT time */
1152 ok = gen_transact(sock, "DELE %d", number);
1153 if (ok != PS_SUCCESS)
1156 rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1157 rec->status = UID_DELETED;
1161 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1162 /* mark a given message as seen */
1165 mark_uid_seen(ctl, number);
1169 static int pop3_logout(int sock, struct query *ctl)
1170 /* send logout command */
1174 ok = gen_transact(sock, "QUIT");
1181 static const struct method pop3 =
1183 "POP3", /* Post Office Protocol v3 */
1184 "pop3", /* port for plain and TLS POP3 */
1185 "pop3s", /* port for SSL POP3 */
1186 FALSE, /* this is not a tagged protocol */
1187 TRUE, /* this uses a message delimiter */
1188 pop3_ok, /* parse command response */
1189 pop3_getauth, /* get authorization */
1190 pop3_getrange, /* query range of messages */
1191 pop3_getsizes, /* we can get a list of sizes */
1192 pop3_getpartialsizes, /* we can get the size of 1 mail */
1193 pop3_is_old, /* how do we tell a message is old? */
1194 pop3_fetch, /* request given message */
1195 NULL, /* no way to fetch body alone */
1196 NULL, /* no message trailer */
1197 pop3_delete, /* how to delete a message */
1198 pop3_mark_seen, /* how to mark a message as seen */
1199 NULL, /* no action at end of mailbox */
1200 pop3_logout, /* log out, we're done */
1201 FALSE, /* no, we can't re-poll */
1204 int doPOP3 (struct query *ctl)
1205 /* retrieve messages using POP3 */
1208 if (ctl->mailboxes->id) {
1209 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1214 return(do_protocol(ctl, &pop3));
1216 #endif /* POP3_ENABLE */
1218 /* pop3.c ends here */