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, '<');
274 GT_("Required APOP timestamp not found in greeting\n"));
278 /* find end of timestamp */
279 end = strchr(start + 1, '>');
281 if (!end || end == start + 1) {
283 GT_("Timestamp syntax error in greeting\n"));
289 /* SECURITY: 2007-03-17
290 * Strictly validating the presented challenge for RFC-822
291 * conformity (it must be a msg-id in terms of that standard) is
292 * supposed to make attacks against the MD5 implementation
295 * [1] "Security vulnerability in APOP authentication",
296 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
297 if (!rfc822_valid_msgid((unsigned char *)start)) {
299 GT_("Invalid APOP timestamp.\n"));
303 /* copy timestamp and password into digestion buffer */
304 char *msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
306 strcat(msg,ctl->password);
307 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
310 return gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
313 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
314 /* apply for connection authorization */
319 #endif /* OPIE_ENABLE */
321 flag connection_may_have_tls_errors = FALSE;
322 #endif /* SSL_ENABLE */
327 #endif /* defined(GSSAPI) */
328 #if defined(KERBEROS_V5)
329 has_kerberos = FALSE;
330 #endif /* defined(KERBEROS_V5) */
334 #endif /* OPIE_ENABLE */
337 #endif /* SSL_ENABLE */
339 /* Set this up before authentication quits early. */
340 set_peek_capable(ctl);
342 /* Hack: allow user to force RETR. */
343 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
348 * The "Maillennium POP3/PROXY server" deliberately truncates
349 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
350 * disable TOP. Comcast once spewed marketing babble to the extent
351 * of protecting Outlook -- pretty overzealous to break a protocol
352 * for that that Microsoft could have read, too. Comcast aren't
353 * alone in using this software though.
354 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
355 * (Thanks to Ed Wilts for reminding me of that.)
357 * The warning is printed once per server, until fetchmail exits.
358 * It will be suppressed when --fetchall or other circumstances make
359 * us use RETR anyhow.
363 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
364 if ((ctl->server.workarounds & WKA_TOP) == 0) {
365 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
366 ctl->server.workarounds |= WKA_TOP;
370 if (ctl->server.authenticate == A_SSH) {
376 * This needs to catch both demon.co.uk and demon.net.
377 * If we see either, and we're in multidrop mode, try to use
378 * the SDPS *ENV extension.
380 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
381 ctl->server.sdps = TRUE;
382 #endif /* SDPS_ENABLE */
384 /* this is a leftover from the times 6.3.X and older when APOP was a
385 * "protocol" (P_APOP) rather than an authenticator (A_APOP),
386 * however, the switch is still useful because we can break; after
387 * an authenticator failed. */
388 switch (ctl->server.protocol) {
391 /* XXX FIXME: AUTH probing (RFC1734) should become global */
392 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
393 if (strstr(ctl->remotename, "@compuserve.com"))
395 /* AUTH command should return a list of available mechanisms */
396 if (gen_transact(sock, "AUTH") == 0)
399 flag has_rpa = FALSE;
401 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
405 if (strncasecmp(buffer, "rpa", 3) == 0)
408 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
409 ctl->password, sock))
415 #endif /* RPA_ENABLE */
418 * CAPA command may return a list including available
419 * authentication mechanisms and STLS capability.
421 * If it doesn't, no harm done, we just fall back to a plain
422 * login -- if the user allows it.
424 * Note that this code latches the server's authentication type,
425 * so that in daemon mode the CAPA check only needs to be done
426 * once at start of run.
428 * If CAPA fails, then force the authentication method to
429 * PASSWORD, switch off opportunistic and repoll immediately.
430 * If TLS is mandatory, fail up front.
432 if ((ctl->server.authenticate == A_ANY) ||
433 (ctl->server.authenticate == A_GSSAPI) ||
434 (ctl->server.authenticate == A_KERBEROS_V5) ||
435 (ctl->server.authenticate == A_OTP) ||
436 (ctl->server.authenticate == A_CRAM_MD5) ||
439 if ((ok = capa_probe(sock)) != PS_SUCCESS)
440 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
441 if (ok == PS_AUTHFAIL ||
442 /* Some servers directly close the socket. However, if we
443 * have already authenticated before, then a previous CAPA
444 * must have succeeded. In that case, treat this as a
445 * genuine socket error and do not change the auth method.
447 (ok == PS_SOCKET && !ctl->wehaveauthed))
451 /* fail with mandatory STLS without repoll */
452 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
453 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
455 } else if (maybe_tls(ctl)) {
456 /* defeat opportunistic STLS */
457 xfree(ctl->sslproto);
458 ctl->sslproto = xstrdup("");
461 /* If strong authentication was opportunistic, retry without, else fail. */
462 switch (ctl->server.authenticate) {
464 ctl->server.authenticate = A_PASSWORD;
466 case A_PASSWORD: /* this should only happen with TLS enabled */
475 if (maybe_tls(ctl)) {
478 commonname = ctl->server.pollname;
480 commonname = ctl->server.via;
481 if (ctl->sslcommonname)
482 commonname = ctl->sslcommonname;
485 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
487 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
488 * protocol that will work with STARTTLS. Don't need to worry
489 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
491 if (gen_transact(sock, "STLS") == PS_SUCCESS
492 && (set_timeout(mytimeout), SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
493 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
494 ctl->server.pollname, &ctl->remotename)) != -1)
497 * RFC 2595 says this:
499 * "Once TLS has been started, the client MUST discard cached
500 * information about server capabilities and SHOULD re-issue the
501 * CAPABILITY command. This is necessary to protect against
502 * man-in-the-middle attacks which alter the capabilities list prior
503 * to STARTTLS. The server MAY advertise different capabilities
506 * Now that we're confident in our TLS connection we can
507 * guarantee a secure capability re-probe.
511 ok = capa_probe(sock);
512 if (ok != PS_SUCCESS) {
515 if (outlevel >= O_VERBOSE)
517 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
519 } else if (must_tls(ctl)) {
520 /* Config required TLS but we couldn't guarantee it, so we must
523 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
526 /* We don't know whether the connection is usable, and there's
527 * no command we can reasonably issue to test it (NOOP isn't
528 * allowed til post-authentication), so leave it in an unknown
529 * state, mark it as such, and check more carefully if things
530 * go wrong when we try to authenticate. */
532 connection_may_have_tls_errors = TRUE;
533 if (outlevel >= O_VERBOSE)
535 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
540 #endif /* SSL_ENABLE */
543 * OK, we have an authentication type now.
548 (ctl->server.authenticate == A_GSSAPI ||
549 (ctl->server.authenticate == A_ANY
550 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
552 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
553 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
556 #endif /* defined(GSSAPI) */
560 (ctl->server.authenticate == A_OTP ||
561 ctl->server.authenticate == A_ANY))
563 ok = do_otp(sock, "AUTH", ctl);
564 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
567 #endif /* OPIE_ENABLE */
570 /* MSN servers require the use of NTLM (MSN) authentication */
571 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
572 ctl->server.authenticate == A_MSN)
573 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
574 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
575 ok = do_pop3_ntlm(sock, ctl, 0);
576 if (ok == 0 || ctl->server.authenticate != A_ANY)
580 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
583 GT_("Required NTLM capability not compiled into fetchmail\n"));
587 if (ctl->server.authenticate == A_CRAM_MD5 ||
588 (has_cram && ctl->server.authenticate == A_ANY))
590 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
591 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
595 if (ctl->server.authenticate == A_APOP
596 || ctl->server.authenticate == A_ANY)
598 ok = do_apop(sock, ctl, greeting);
599 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
603 /* ordinary validation, no one-time password or RPA */
604 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
608 /* see RFC1938: A One-Time Password System */
609 if ((challenge = strstr(lastok, "otp-"))) {
610 char response[OPIE_RESPONSE_MAX+1];
612 char *n = xstrdup("");
614 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
616 if ((i == -2) && !run.poll_interval) {
617 char secret[OPIE_SECRET_MAX+1];
618 fprintf(stderr, GT_("Secret pass phrase: "));
619 if (opiereadpass(secret, sizeof(secret), 0))
620 i = opiegenerator(challenge, secret, response);
621 memset(secret, 0, sizeof(secret));
629 ok = gen_transact(sock, "PASS %s", response);
632 #endif /* OPIE_ENABLE */
634 /* KPOP uses out-of-band authentication and does not check what
635 * we send here, so send some random fixed string, to avoid
636 * users switching *to* KPOP accidentally revealing their
638 if ((ctl->server.authenticate == A_ANY
639 || ctl->server.authenticate == A_KERBEROS_V5)
640 && (ctl->server.service != NULL
641 && strcmp(ctl->server.service, KPOP_PORT) == 0))
643 ok = gen_transact(sock, "PASS krb_ticket");
647 /* check if we are actually allowed to send the password */
648 if (ctl->server.authenticate == A_ANY
649 || ctl->server.authenticate == A_PASSWORD) {
650 strlcpy(shroud, ctl->password, sizeof(shroud));
651 ok = gen_transact(sock, "PASS %s", ctl->password);
653 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
656 memset(shroud, 0x55, sizeof(shroud));
661 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
666 /* this is for servers which claim to support TLS, but actually
668 if (connection_may_have_tls_errors
669 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
671 xfree(ctl->sslproto);
672 ctl->sslproto = xstrdup("");
673 /* repoll immediately without TLS */
680 /* maybe we detected a lock-busy condition? */
681 if (ok == PS_LOCKBUSY)
682 report(stderr, GT_("lock busy! Is another session active?\n"));
691 /* cut off C string at first POSIX space */
692 static void trim(char *s) {
693 s += strcspn(s, POSIX_space);
697 /** Parse the UID response (leading +OK must have been
698 * stripped off) in buf, store the number in gotnum, and store the ID
699 * into the caller-provided buffer "id" of size "idsize".
700 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
701 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
706 /* skip leading blanks ourselves */
708 i += strspn(i, POSIX_space);
710 *gotnum = strtoul(i, &j, 10);
711 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
712 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
715 j += strspn(j, POSIX_space);
716 strlcpy(id, j, idsize);
721 /** request UIDL for single message \a num and stuff the result into the
722 * buffer \a id which can hold \a idsize bytes */
723 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
726 char buf [POPBUFSIZE+1];
727 unsigned long gotnum;
729 gen_send(sock, "UIDL %d", num);
730 if ((ok = pop3_ok(sock, buf)) != 0)
732 if ((ok = parseuid(buf, &gotnum, id, idsize)))
734 if (gotnum != (unsigned long)num) {
735 report(stderr, GT_("Server responded with UID for wrong message.\n"));
741 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
744 unsigned int first_nr, last_nr, try_nr;
749 while (first_nr < last_nr - 1)
751 struct uid_db_record *rec;
753 try_nr = (first_nr + last_nr) / 2;
754 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
756 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
758 flag mark = rec->status;
759 if (mark == UID_DELETED || mark == UID_EXPUNGED)
761 if (outlevel >= O_VERBOSE)
762 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
763 /* just mark it as seen now! */
764 rec->status = mark = UID_SEEN;
767 /* narrow the search region! */
768 if (mark == UID_UNSEEN)
770 if (outlevel >= O_DEBUG)
771 report(stdout, GT_("%u is unseen\n"), try_nr);
777 /* save the number */
778 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
782 if (outlevel >= O_DEBUG)
783 report(stdout, GT_("%u is unseen\n"), try_nr);
787 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
788 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
791 if (outlevel >= O_DEBUG && last_nr <= count)
792 report(stdout, GT_("%u is first unseen\n"), last_nr);
795 *newp = count - first_nr;
800 static int pop3_getrange(int sock,
803 int *countp, int *newp, int *bytes)
804 /* get range of messages to be fetched */
807 char buf [POPBUFSIZE+1];
810 /* Ensure that the new list is properly empty */
811 clear_uid_db(&ctl->newsaved);
814 /* Alain Knaff suggests this, but it's not RFC standard */
816 if ((ok = gen_transact(sock, "MBOX %s", folder)))
820 /* get the total message count */
821 gen_send(sock, "STAT");
822 ok = pop3_ok(sock, buf);
826 asgn = sscanf(buf,"%d %d", countp, bytes);
832 /* unless fetching all mail, get UID list (UIDL) */
840 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
841 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
843 /* should we do fast uidl this time? */
844 fastuidl = ctl->fastuidl;
845 if (*countp > 7 && /* linear search is better if there are few mails! */
846 !ctl->fetchall && /* with fetchall, all uids are required */
847 !ctl->flush && /* with flush, it is safer to disable fastuidl */
848 NUM_NONZERO (fastuidl))
853 dofastuidl = ctl->fastuidlcount != 0;
861 return(pop3_fastuidl( sock, ctl, *countp, newp));
862 /* grab the mailbox's UID list */
863 if (gen_transact(sock, "UIDL") != 0)
865 if (!ctl->fetchall) {
866 report(stderr, GT_("protocol error while fetching UIDLs\n"));
872 /* UIDL worked - parse reply */
876 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
881 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
883 struct uid_db_record *old_rec, *new_rec;
885 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
887 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
889 flag mark = old_rec->status;
890 if (mark == UID_DELETED || mark == UID_EXPUNGED)
892 /* XXX FIXME: switch 3 occurrences from
893 * (int)unum or (unsigned int)unum to
894 * remove the cast and use %lu - not now
895 * though, time for new release */
896 if (outlevel >= O_VERBOSE)
897 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
898 /* just mark it as seen now! */
899 old_rec->status = mark = UID_SEEN;
901 new_rec->status = mark;
902 if (mark == UID_UNSEEN)
905 if (outlevel >= O_DEBUG)
906 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
912 if (outlevel >= O_DEBUG)
913 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
914 /* add it to oldsaved also! In case, we do not
915 * swap the lists (say, due to socket error),
916 * the same mail will not be downloaded again.
918 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
922 * save the number if it will be needed later on
923 * (messsage will either be fetched or deleted)
925 if (new_rec->status == UID_UNSEEN || ctl->flush) {
926 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
927 set_uid_db_num(&ctl->newsaved, new_rec, unum);
931 } /* multi-line loop for UIDL reply */
939 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
940 /* capture the size of message #first */
943 char buf [POPBUFSIZE+1];
946 for (i = first; i <= last; i++) {
947 gen_send(sock, "LIST %d", i);
948 if ((ok = pop3_ok(sock, buf)) != 0)
950 if (sscanf(buf, "%d %u", &num, &size) == 2) {
952 sizes[i - first] = size;
954 /* warn about possible attempt to induce buffer overrun
956 * we expect server reply message number and requested
957 * message number to match */
958 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
964 static int pop3_getsizes(int sock, int count, int *sizes)
965 /* capture the sizes of all messages */
969 if ((ok = gen_transact(sock, "LIST")) != 0)
973 char buf [POPBUFSIZE+1];
975 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
977 unsigned int num, size;
981 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
982 if (num > 0 && num <= (unsigned)count)
983 sizes[num - 1] = size;
985 /* warn about possible attempt to induce buffer overrun */
986 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
994 static int pop3_is_old(int sock, struct query *ctl, int num)
995 /* is the given message old? */
997 struct uid_db_record *rec;
999 if (!uid_db_n_records(&ctl->oldsaved))
1000 return (num <= last);
1001 else if (dofastuidl)
1008 /* in fast uidl, we manipulate the old list only! */
1009 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1011 /* we already have the id! */
1012 return(rec->status != UID_UNSEEN);
1015 /* get the uidl first! */
1016 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1019 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1020 /* we already have the id! */
1021 set_uid_db_num(&ctl->oldsaved, rec, num);
1022 return(rec->status != UID_UNSEEN);
1026 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1027 set_uid_db_num(&ctl->oldsaved, rec, num);
1031 rec = find_uid_by_num(&ctl->newsaved, num);
1032 return !rec || rec->status != UID_UNSEEN;
1036 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1037 /* request nth message */
1040 char buf[POPBUFSIZE+1];
1044 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1045 * for a description of what we're parsing here.
1046 * -- updated 2006-02-22
1048 if (ctl->server.sdps)
1052 sdps_envfrom = (char *)NULL;
1053 sdps_envto = (char *)NULL;
1054 gen_send(sock, "*ENV %d", number);
1056 if (gen_recv(sock, buf, sizeof(buf)))
1061 switch (linecount) {
1063 /* No need to wrap envelope from address */
1064 /* FIXME: some parts of fetchmail don't handle null
1065 * envelope senders, so use <> to mark null sender
1066 * as a workaround. */
1067 if (strspn(buf, " \t") == strlen(buf))
1069 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1070 strcpy(sdps_envfrom,buf);
1073 /* Wrap address with To: <> so nxtaddr() likes it */
1074 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1075 sprintf(sdps_envto,"To: <%s>",buf);
1079 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1083 #endif /* SDPS_ENABLE */
1086 * Though the POP RFCs don't document this fact, on almost every
1087 * POP3 server I know of messages are marked "seen" only at the
1088 * time the OK response to a RETR is issued.
1090 * This means we can use TOP to fetch the message without setting its
1091 * seen flag. This is good! It means that if the protocol exchange
1092 * craps out during the message, it will still be marked `unseen' on
1093 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1094 * reported to mark messages seen on a TOP fetch.)
1096 * However...*don't* do this if we're using keep to suppress deletion!
1097 * In that case, marking the seen flag is the only way to prevent the
1098 * message from being re-fetched on subsequent runs.
1100 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1101 * This gives us a workaround for servers like usa.net's that bungle
1102 * TOP. It's pretty harmless because fetchall guarantees that any
1103 * message dropped by an interrupted RETR will be picked up on the
1104 * next poll of the site.
1106 * We take advantage here of the fact that, according to all the
1107 * POP RFCs, "if the number of lines requested by the POP3 client
1108 * is greater than than the number of lines in the body, then the
1109 * POP3 server sends the entire message.").
1111 * The line count passed (99999999) is the maximum value CompuServe will
1112 * accept; it's much lower than the natural value 2147483646 (the maximum
1113 * twos-complement signed 32-bit integer minus 1) */
1115 gen_send(sock, "RETR %d", number);
1117 gen_send(sock, "TOP %d 99999999", number);
1118 if ((ok = pop3_ok(sock, buf)) != 0)
1121 *lenp = -1; /* we got sizes from the LIST response */
1126 static void mark_uid_seen(struct query *ctl, int number)
1127 /* Tell the UID code we've seen this. */
1129 struct uid_db_record *rec;
1131 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1132 rec->status = UID_SEEN;
1133 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1134 * (say, due to socket error), the same mail will not be downloaded
1137 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1138 rec->status = UID_SEEN;
1141 static int pop3_delete(int sock, struct query *ctl, int number)
1142 /* delete a given message */
1144 struct uid_db_record *rec;
1146 mark_uid_seen(ctl, number);
1147 /* actually, mark for deletion -- doesn't happen until QUIT time */
1148 ok = gen_transact(sock, "DELE %d", number);
1149 if (ok != PS_SUCCESS)
1152 rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1153 rec->status = UID_DELETED;
1157 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1158 /* mark a given message as seen */
1161 mark_uid_seen(ctl, number);
1165 static int pop3_logout(int sock, struct query *ctl)
1166 /* send logout command */
1170 ok = gen_transact(sock, "QUIT");
1177 static const struct method pop3 =
1179 "POP3", /* Post Office Protocol v3 */
1180 "pop3", /* port for plain and TLS POP3 */
1181 "pop3s", /* port for SSL POP3 */
1182 FALSE, /* this is not a tagged protocol */
1183 TRUE, /* this uses a message delimiter */
1184 pop3_ok, /* parse command response */
1185 pop3_getauth, /* get authorization */
1186 pop3_getrange, /* query range of messages */
1187 pop3_getsizes, /* we can get a list of sizes */
1188 pop3_getpartialsizes, /* we can get the size of 1 mail */
1189 pop3_is_old, /* how do we tell a message is old? */
1190 pop3_fetch, /* request given message */
1191 NULL, /* no way to fetch body alone */
1192 NULL, /* no message trailer */
1193 pop3_delete, /* how to delete a message */
1194 pop3_mark_seen, /* how to mark a message as seen */
1195 NULL, /* no action at end of mailbox */
1196 pop3_logout, /* log out, we're done */
1197 FALSE, /* no, we can't re-poll */
1200 int doPOP3 (struct query *ctl)
1201 /* retrieve messages using POP3 */
1204 if (ctl->mailboxes->id) {
1205 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1210 return(do_protocol(ctl, &pop3));
1212 #endif /* POP3_ENABLE */
1214 /* pop3.c ends here */