2 * pop3.c -- POP3 protocol methods
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
13 #if defined(HAVE_UNISTD_H)
16 #if defined(STDC_HEADERS)
21 #include "fetchmail.h"
33 #endif /* OPIE_ENABLE */
35 /* global variables: please reinitialize them explicitly for proper
36 * working in daemon mode */
38 /* TODO: session variables to be initialized before server greeting */
40 static char lastok[POPBUFSIZE+1];
41 #endif /* OPIE_ENABLE */
43 /* session variables initialized in capa_probe() or pop3_getauth() */
44 flag done_capa = FALSE;
46 flag has_gssapi = FALSE;
47 #endif /* defined(GSSAPI) */
48 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
49 flag has_kerberos = FALSE;
50 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
51 static flag has_cram = FALSE;
54 #endif /* OPIE_ENABLE */
56 static flag has_stls = FALSE;
57 #endif /* SSL_ENABLE */
59 /* mailbox variables initialized in pop3_getrange() */
62 /* mail variables initialized in pop3_fetch() */
66 #endif /* SDPS_ENABLE */
72 * NTLM support by Grant Edwards.
74 * Handle MS-Exchange NTLM authentication method. This is the same
75 * as the NTLM auth used by Samba for SMB related services. We just
76 * encode the packets in base64 instead of sending them out via a
79 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
82 static int do_pop3_ntlm(int sock, struct query *ctl,
83 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
85 tSmbNtlmAuthRequest request;
86 tSmbNtlmAuthChallenge challenge;
87 tSmbNtlmAuthResponse response;
92 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
94 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
100 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
102 if (outlevel >= O_DEBUG)
103 dumpSmbNtlmAuthRequest(stdout, &request);
105 memset(msgbuf,0,sizeof msgbuf);
106 to64frombits (msgbuf, &request, SmbLength(&request));
108 if (outlevel >= O_MONITOR)
109 report(stdout, "POP3> %s\n", msgbuf);
111 strcat(msgbuf,"\r\n");
112 SockWrite (sock, msgbuf, strlen (msgbuf));
114 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
117 len = from64tobits (&challenge, msgbuf, sizeof(msgbuf));
119 if (outlevel >= O_DEBUG)
120 dumpSmbNtlmAuthChallenge(stdout, &challenge);
122 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
124 if (outlevel >= O_DEBUG)
125 dumpSmbNtlmAuthResponse(stdout, &response);
127 memset(msgbuf,0,sizeof msgbuf);
128 to64frombits (msgbuf, &response, SmbLength(&response));
130 if (outlevel >= O_MONITOR)
131 report(stdout, "POP3> %s\n", msgbuf);
133 strcat(msgbuf,"\r\n");
134 SockWrite (sock, msgbuf, strlen (msgbuf));
136 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
139 if (strstr (msgbuf, "OK"))
147 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
149 static int pop3_ok (int sock, char *argbuf)
150 /* parse command response */
153 char buf [POPBUFSIZE+1];
156 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
158 if (*bufp == '+' || *bufp == '-')
163 while (isalpha((unsigned char)*bufp))
169 if (strcmp(buf,"+OK") == 0)
172 strcpy(lastok, bufp);
173 #endif /* OPIE_ENABLE */
176 else if (strncmp(buf,"-ERR", 4) == 0)
178 if (stage == STAGE_FETCH)
180 else if (stage > STAGE_GETAUTH)
183 * We're checking for "lock busy", "unable to lock",
184 * "already locked", "wait a few minutes" etc. here.
185 * This indicates that we have to wait for the server to
186 * unwedge itself before we can poll again.
188 * PS_LOCKBUSY check empirically verified with two recent
189 * versions of the Berkeley popper; QPOP (version 2.2) and
190 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
191 * These are caught by the case-indifferent "lock" check.
192 * The "wait" catches "mail storage services unavailable,
193 * wait a few minutes and try again" on the InterMail server.
195 * If these aren't picked up on correctly, fetchmail will
196 * think there is an authentication failure and wedge the
197 * connection in order to prevent futile polls.
201 else if (strstr(bufp,"lock")
202 || strstr(bufp,"Lock")
203 || strstr(bufp,"LOCK")
204 || strstr(bufp,"wait")
205 /* these are blessed by RFC 2449 */
206 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
208 else if ((strstr(bufp,"Service")
209 || strstr(bufp,"service"))
210 && (strstr(bufp,"unavailable")))
215 * We always want to pass the user lock-busy messages, because
216 * they're red flags. Other stuff (like AUTH failures on non-
217 * RFC1734 servers) only if we're debugging.
219 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
220 report(stderr, "%s\n", bufp);
225 #if POPBUFSIZE > MSGBUFSIZE
226 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
237 static int capa_probe(int sock)
238 /* probe the capabilities of the remote server */
247 #endif /* defined(GSSAPI) */
248 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
249 has_kerberos = FALSE;
250 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
254 #endif /* OPIE_ENABLE */
256 ok = gen_transact(sock, "CAPA");
257 if (ok == PS_SUCCESS)
261 /* determine what authentication methods we have available */
262 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
267 if (strstr(buffer, "STLS"))
269 #endif /* SSL_ENABLE */
271 if (strstr(buffer, "GSSAPI"))
273 #endif /* defined(GSSAPI) */
274 #if defined(KERBEROS_V4)
275 if (strstr(buffer, "KERBEROS_V4"))
277 #endif /* defined(KERBEROS_V4) */
279 if (strstr(buffer, "X-OTP"))
281 #endif /* OPIE_ENABLE */
282 if (strstr(buffer, "CRAM-MD5"))
290 static void set_peek_capable(struct query *ctl)
292 /* we're peek-capable means that the use of TOP is enabled,
293 * see pop3_fetch for details - short story, we can use TOP if
294 * we have a means of reliably tracking which mail we need to
295 * refetch should the connection abort in the middle.
296 * fetchall forces RETR, as does keep without UIDL */
297 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
300 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
301 /* apply for connection authorization */
308 #endif /* OPIE_ENABLE */
310 flag connection_may_have_tls_errors = FALSE;
311 flag got_tls = FALSE;
312 #endif /* SSL_ENABLE */
317 #endif /* defined(GSSAPI) */
318 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
319 has_kerberos = FALSE;
320 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
324 #endif /* OPIE_ENABLE */
327 #endif /* SSL_ENABLE */
329 /* Set this up before authentication quits early. */
330 set_peek_capable(ctl);
332 /* Hack: allow user to force RETR. */
333 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
338 * The "Maillennium POP3/PROXY server" deliberately truncates
339 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
340 * disable TOP. Comcast once spewed marketing babble to the extent
341 * of protecting Outlook -- pretty overzealous to break a protocol
342 * for that that Microsoft could have read, too. Comcast aren't
343 * alone in using this software though.
344 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
345 * (Thanks to Ed Wilts for reminding me of that.)
347 * The warning is printed once per server, until fetchmail exits.
348 * It will be suppressed when --fetchall or other circumstances make
349 * us use RETR anyhow.
353 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
354 if ((ctl->server.workarounds & WKA_TOP) == 0) {
355 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
356 ctl->server.workarounds |= WKA_TOP;
360 if (ctl->server.authenticate == A_SSH) {
366 * This needs to catch both demon.co.uk and demon.net.
367 * If we see either, and we're in multidrop mode, try to use
368 * the SDPS *ENV extension.
370 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
371 ctl->server.sdps = TRUE;
372 #endif /* SDPS_ENABLE */
375 /* MSN servers require the use of NTLM (MSN) authentication */
376 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
377 ctl->server.authenticate == A_MSN)
378 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
379 if (ctl->server.authenticate == A_NTLM)
380 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
382 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
385 GT_("Required NTLM capability not compiled into fetchmail\n"));
389 switch (ctl->server.protocol) {
392 /* XXX FIXME: AUTH probing (RFC1734) should become global */
393 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
394 if (strstr(ctl->remotename, "@compuserve.com"))
396 /* AUTH command should return a list of available mechanisms */
397 if (gen_transact(sock, "AUTH") == 0)
400 flag has_rpa = FALSE;
402 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
406 if (strncasecmp(buffer, "rpa", 3) == 0)
409 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
410 ctl->password, sock))
416 #endif /* RPA_ENABLE */
419 * CAPA command may return a list including available
420 * authentication mechanisms and STLS capability.
422 * If it doesn't, no harm done, we just fall back to a plain
423 * login -- if the user allows it.
425 * Note that this code latches the server's authentication type,
426 * so that in daemon mode the CAPA check only needs to be done
427 * once at start of run.
429 * If CAPA fails, then force the authentication method to
430 * PASSWORD, switch off opportunistic and repoll immediately.
431 * If TLS is mandatory, fail up front.
433 if ((ctl->server.authenticate == A_ANY) ||
434 (ctl->server.authenticate == A_GSSAPI) ||
435 (ctl->server.authenticate == A_KERBEROS_V4) ||
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;
488 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
489 * protocol that will work with STARTTLS. Don't need to worry
490 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
492 if (gen_transact(sock, "STLS") == PS_SUCCESS
493 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
494 ctl->sslcertpath, ctl->sslfingerprint, commonname,
495 ctl->server.pollname, &ctl->remotename) != -1)
498 * RFC 2595 says this:
500 * "Once TLS has been started, the client MUST discard cached
501 * information about server capabilities and SHOULD re-issue the
502 * CAPABILITY command. This is necessary to protect against
503 * man-in-the-middle attacks which alter the capabilities list prior
504 * to STARTTLS. The server MAY advertise different capabilities
507 * Now that we're confident in our TLS connection we can
508 * guarantee a secure capability re-probe.
512 ok = capa_probe(sock);
513 if (ok != PS_SUCCESS) {
516 if (outlevel >= O_VERBOSE)
518 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
525 /* Config required TLS but we couldn't guarantee it, so we must
527 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
530 /* We don't know whether the connection is usable, and there's
531 * no command we can reasonably issue to test it (NOOP isn't
532 * allowed til post-authentication), so leave it in an unknown
533 * state, mark it as such, and check more carefully if things
534 * go wrong when we try to authenticate. */
535 connection_may_have_tls_errors = TRUE;
536 if (outlevel >= O_VERBOSE)
538 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
543 #endif /* SSL_ENABLE */
546 * OK, we have an authentication type now.
548 #if defined(KERBEROS_V4)
550 * Servers doing KPOP have to go through a dummy login sequence
551 * rather than doing SASL.
554 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
555 && (ctl->server.authenticate == A_KERBEROS_V4
556 || ctl->server.authenticate == A_KERBEROS_V5
557 || ctl->server.authenticate == A_ANY))
559 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
560 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
563 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
567 (ctl->server.authenticate == A_GSSAPI ||
568 ctl->server.authenticate == A_ANY))
570 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
571 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
574 #endif /* defined(GSSAPI) */
578 (ctl->server.authenticate == A_OTP ||
579 ctl->server.authenticate == A_ANY))
581 ok = do_otp(sock, "AUTH", ctl);
582 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
585 #endif /* OPIE_ENABLE */
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 /* ordinary validation, no one-time password or RPA */
596 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
600 /* see RFC1938: A One-Time Password System */
601 if ((challenge = strstr(lastok, "otp-"))) {
602 char response[OPIE_RESPONSE_MAX+1];
604 char *n = xstrdup("");
606 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
608 if ((i == -2) && !run.poll_interval) {
609 char secret[OPIE_SECRET_MAX+1];
610 fprintf(stderr, GT_("Secret pass phrase: "));
611 if (opiereadpass(secret, sizeof(secret), 0))
612 i = opiegenerator(challenge, secret, response);
613 memset(secret, 0, sizeof(secret));
621 ok = gen_transact(sock, "PASS %s", response);
624 #endif /* OPIE_ENABLE */
626 /* KPOP uses out-of-band authentication and does not check what
627 * we send here, so send some random fixed string, to avoid
628 * users switching *to* KPOP accidentally revealing their
630 if ((ctl->server.authenticate == A_ANY
631 || ctl->server.authenticate == A_KERBEROS_V4
632 || ctl->server.authenticate == A_KERBEROS_V5)
633 && (ctl->server.service != NULL
634 && strcmp(ctl->server.service, KPOP_PORT) == 0))
636 ok = gen_transact(sock, "PASS krb_ticket");
640 /* check if we are actually allowed to send the password */
641 if (ctl->server.authenticate == A_ANY
642 || ctl->server.authenticate == A_PASSWORD) {
643 strlcpy(shroud, ctl->password, sizeof(shroud));
644 ok = gen_transact(sock, "PASS %s", ctl->password);
646 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
649 memset(shroud, 0x55, sizeof(shroud));
654 /* build MD5 digest from greeting timestamp + password */
655 /* find start of timestamp */
656 for (start = greeting; *start != 0 && *start != '<'; start++)
660 GT_("Required APOP timestamp not found in greeting\n"));
664 /* find end of timestamp */
665 for (end = start; *end != 0 && *end != '>'; end++)
667 if (*end == 0 || end == start + 1) {
669 GT_("Timestamp syntax error in greeting\n"));
675 /* SECURITY: 2007-03-17
676 * Strictly validating the presented challenge for RFC-822
677 * conformity (it must be a msg-id in terms of that standard) is
678 * supposed to make attacks against the MD5 implementation
681 * [1] "Security vulnerability in APOP authentication",
682 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
683 if (!rfc822_valid_msgid((unsigned char *)start)) {
685 GT_("Invalid APOP timestamp.\n"));
689 /* copy timestamp and password into digestion buffer */
690 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
692 strcat(msg,ctl->password);
693 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
696 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
700 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
701 strlcpy(shroud, ctl->password, sizeof(shroud));
702 ok = gen_transact(sock, "RPOP %s", ctl->password);
703 memset(shroud, 0x55, sizeof(shroud));
709 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
714 /* this is for servers which claim to support TLS, but actually
716 if (connection_may_have_tls_errors
717 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
719 xfree(ctl->sslproto);
720 ctl->sslproto = xstrdup("");
721 /* repoll immediately without TLS */
728 /* maybe we detected a lock-busy condition? */
729 if (ok == PS_LOCKBUSY)
730 report(stderr, GT_("lock busy! Is another session active?\n"));
735 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
736 * accepted by Matthias Andree.
738 * Rationale: the server must have locked the spool before returning +OK;
739 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
742 * Empirical experience shows some server/OS combinations
743 * may need a brief pause even after any lockfiles on the
744 * server are released, to give the server time to finish
745 * copying back very large mailfolders from the temp-file...
746 * this is only ever an issue with extremely large mailboxes.
748 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
755 /* cut off C string at first POSIX space */
756 static void trim(char *s) {
757 s += strcspn(s, POSIX_space);
761 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
762 * broken messages) do not have Message-ID headers, and messages without
763 * those appear to break this code and cause fetchmail (at least version
764 * 6.2.3) to not delete such messages properly after retrieval.
765 * See Sourceforge Bug #780933.
767 * The other problem is that the TOP command itself is optional, too... */
768 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
772 char buf [POPBUFSIZE+1];
773 snprintf(buf, sizeof(buf), "TOP %d 1", num);
774 if ((ok = gen_transact(sock, "%s", buf)) != 0)
777 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
781 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
784 p += strspn(p, POSIX_space);
785 strlcpy(id, p, idsize);
789 /* XXX FIXME: do not return success here if no Message-ID header was
794 /** Parse the UID response (leading +OK must have been
795 * stripped off) in buf, store the number in gotnum, and store the ID
796 * into the caller-provided buffer "id" of size "idsize".
797 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
798 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
803 /* skip leading blanks ourselves */
805 i += strspn(i, POSIX_space);
807 *gotnum = strtoul(i, &j, 10);
808 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
809 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
812 j += strspn(j, POSIX_space);
813 strlcpy(id, j, idsize);
818 /** request UIDL for single message \a num and stuff the result into the
819 * buffer \a id which can hold \a idsize bytes */
820 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
823 char buf [POPBUFSIZE+1];
824 unsigned long gotnum;
826 gen_send(sock, "UIDL %d", num);
827 if ((ok = pop3_ok(sock, buf)) != 0)
829 if ((ok = parseuid(buf, &gotnum, id, idsize)))
831 if (gotnum != (unsigned long)num) {
832 report(stderr, GT_("Server responded with UID for wrong message.\n"));
838 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
841 unsigned int first_nr, last_nr, try_nr;
846 while (first_nr < last_nr - 1)
850 try_nr = (first_nr + last_nr) / 2;
851 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
853 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
855 flag mark = newl->val.status.mark;
856 if (mark == UID_DELETED || mark == UID_EXPUNGED)
858 if (outlevel >= O_VERBOSE)
859 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
860 /* just mark it as seen now! */
861 newl->val.status.mark = mark = UID_SEEN;
864 /* narrow the search region! */
865 if (mark == UID_UNSEEN)
867 if (outlevel >= O_DEBUG)
868 report(stdout, GT_("%u is unseen\n"), try_nr);
874 /* save the number */
875 newl->val.status.num = try_nr;
879 if (outlevel >= O_DEBUG)
880 report(stdout, GT_("%u is unseen\n"), try_nr);
884 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
885 newl->val.status.num = try_nr;
888 if (outlevel >= O_DEBUG && last_nr <= count)
889 report(stdout, GT_("%u is first unseen\n"), last_nr);
892 *newp = count - first_nr;
897 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
899 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
900 * message will arrive twice with the same Message-ID, so this
901 * slowuidl code will break. Same goes for messages without
902 * Message-ID headers at all. This code would best be removed. */
903 /* This approach tries to get the message headers from the
904 * remote hosts and compares the message-id to the already known
906 * + if the first message containes a new id, all messages on
907 * the server will be new
908 * + if the first is known, try to estimate the last known message
909 * on the server and check. If this works you know the total number
910 * of messages to get.
911 * + Otherwise run a binary search to determine the last known message
913 int ok, nolinear = 0;
914 int first_nr, list_len, try_id, try_nr, add_id;
918 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
921 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
922 /* the first message is unknown -> all messages are new */
927 /* check where we expect the latest known message */
928 list_len = count_list( &ctl->oldsaved );
929 try_id = list_len - first_nr; /* -1 + 1 */
931 if( try_id <= *countp ) {
932 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
935 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
940 if( try_nr != list_len -1 ) {
941 /* some messages inbetween have been deleted... */
945 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
947 for( ; add_id; add_id >>= 1 ) {
949 if( try_id - add_id <= 1 ) {
956 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
958 try_nr = str_nr_in_list(&ctl->oldsaved, id);
965 GT_("Messages inserted into list on server. Cannot handle this.\n"));
970 /* the first try_id messages are known -> copy them to the newsaved list */
971 for( num = first_nr; num < list_len; num++ )
973 struct idlist *newl = save_str(&ctl->newsaved,
974 str_from_nr_list(&ctl->oldsaved, num),
976 newl->val.status.num = num - first_nr + 1;
980 free_str_list(&ctl->oldsaved);
985 *newp = *countp - try_id;
989 static int pop3_getrange(int sock,
992 int *countp, int *newp, int *bytes)
993 /* get range of messages to be fetched */
996 char buf [POPBUFSIZE+1];
999 /* Ensure that the new list is properly empty */
1000 ctl->newsaved = (struct idlist *)NULL;
1003 /* Alain Knaff suggests this, but it's not RFC standard */
1005 if ((ok = gen_transact(sock, "MBOX %s", folder)))
1009 /* get the total message count */
1010 gen_send(sock, "STAT");
1011 ok = pop3_ok(sock, buf);
1013 sscanf(buf,"%d %d", countp, bytes);
1018 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
1019 * command. We work as hard as possible to hide this, but it makes
1020 * counting new messages intrinsically quadratic in the worst case.
1024 /* if there are messages, and UIDL is desired, use UIDL
1025 * also use UIDL if fetchall is unset */
1026 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
1031 /* should we do fast uidl this time? */
1032 fastuidl = ctl->fastuidl;
1033 if (*countp > 7 && /* linear search is better if there are few mails! */
1034 !ctl->fetchall && /* with fetchall, all uids are required */
1035 !ctl->flush && /* with flush, it is safer to disable fastuidl */
1036 NUM_NONZERO (fastuidl))
1041 dofastuidl = ctl->fastuidlcount != 0;
1046 if (!ctl->server.uidl) {
1047 gen_send(sock, "LAST");
1048 ok = pop3_ok(sock, buf);
1054 /* scan LAST reply */
1055 if (sscanf(buf, "%d", &last) == 0)
1057 report(stderr, GT_("protocol error\n"));
1060 *newp = (*countp - last);
1066 return(pop3_fastuidl( sock, ctl, *countp, newp));
1067 /* grab the mailbox's UID list */
1068 if ((ok = gen_transact(sock, "UIDL")) != 0)
1070 /* don't worry, yet! do it the slow way */
1071 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
1073 report(stderr, GT_("protocol error while fetching UIDLs\n"));
1079 /* UIDL worked - parse reply */
1083 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
1088 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1090 struct idlist *old, *newl;
1092 newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
1093 newl->val.status.num = unum;
1095 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
1097 flag mark = old->val.status.mark;
1098 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1100 /* XXX FIXME: switch 3 occurrences from
1101 * (int)unum or (unsigned int)unum to
1102 * remove the cast and use %lu - not now
1103 * though, time for new release */
1104 if (outlevel >= O_VERBOSE)
1105 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1106 /* just mark it as seen now! */
1107 old->val.status.mark = mark = UID_SEEN;
1109 newl->val.status.mark = mark;
1110 if (mark == UID_UNSEEN)
1113 if (outlevel >= O_DEBUG)
1114 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1120 if (outlevel >= O_DEBUG)
1121 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1122 /* add it to oldsaved also! In case, we do not
1123 * swap the lists (say, due to socket error),
1124 * the same mail will not be downloaded again.
1126 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1128 /* save the number */
1129 old->val.status.num = unum;
1132 } /* multi-line loop for UIDL reply */
1140 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1141 /* capture the size of message #first */
1144 char buf [POPBUFSIZE+1];
1147 for (i = first; i <= last; i++) {
1148 gen_send(sock, "LIST %d", i);
1149 if ((ok = pop3_ok(sock, buf)) != 0)
1151 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1153 sizes[i - first] = size;
1155 /* warn about possible attempt to induce buffer overrun
1157 * we expect server reply message number and requested
1158 * message number to match */
1159 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1165 static int pop3_getsizes(int sock, int count, int *sizes)
1166 /* capture the sizes of all messages */
1170 if ((ok = gen_transact(sock, "LIST")) != 0)
1174 char buf [POPBUFSIZE+1];
1176 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1178 unsigned int num, size;
1182 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1183 if (num > 0 && num <= (unsigned)count)
1184 sizes[num - 1] = size;
1186 /* warn about possible attempt to induce buffer overrun */
1187 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1195 static int pop3_is_old(int sock, struct query *ctl, int num)
1196 /* is the given message old? */
1198 struct idlist *newl;
1200 return (num <= last);
1201 else if (dofastuidl)
1208 /* in fast uidl, we manipulate the old list only! */
1210 if ((newl = id_find(&ctl->oldsaved, num)))
1212 /* we already have the id! */
1213 return(newl->val.status.mark != UID_UNSEEN);
1216 /* get the uidl first! */
1217 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1220 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1221 /* we already have the id! */
1222 newl->val.status.num = num;
1223 return(newl->val.status.mark != UID_UNSEEN);
1227 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1228 newl->val.status.num = num;
1232 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1233 newl->val.status.mark != UID_UNSEEN);
1238 * We could use this to fetch headers only as we do for IMAP. The trouble
1239 * is that there's no way to fetch the body only. So the following RETR
1240 * would have to re-fetch the header. Enough messages have longer headers
1241 * than bodies to make this a net loss.
1243 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1244 /* request headers of nth message */
1247 char buf[POPBUFSIZE+1];
1249 gen_send(sock, "TOP %d 0", number);
1250 if ((ok = pop3_ok(sock, buf)) != 0)
1253 *lenp = -1; /* we got sizes from the LIST response */
1259 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1260 /* request nth message */
1263 char buf[POPBUFSIZE+1];
1267 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1268 * for a description of what we're parsing here.
1269 * -- updated 2006-02-22
1271 if (ctl->server.sdps)
1275 sdps_envfrom = (char *)NULL;
1276 sdps_envto = (char *)NULL;
1277 gen_send(sock, "*ENV %d", number);
1279 if (gen_recv(sock, buf, sizeof(buf)))
1284 switch (linecount) {
1286 /* No need to wrap envelope from address */
1287 /* FIXME: some parts of fetchmail don't handle null
1288 * envelope senders, so use <> to mark null sender
1289 * as a workaround. */
1290 if (strspn(buf, " \t") == strlen(buf))
1292 sdps_envfrom = xmalloc(strlen(buf)+1);
1293 strcpy(sdps_envfrom,buf);
1296 /* Wrap address with To: <> so nxtaddr() likes it */
1297 sdps_envto = xmalloc(strlen(buf)+7);
1298 sprintf(sdps_envto,"To: <%s>",buf);
1302 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1306 #endif /* SDPS_ENABLE */
1309 * Though the POP RFCs don't document this fact, on almost every
1310 * POP3 server I know of messages are marked "seen" only at the
1311 * time the OK response to a RETR is issued.
1313 * This means we can use TOP to fetch the message without setting its
1314 * seen flag. This is good! It means that if the protocol exchange
1315 * craps out during the message, it will still be marked `unseen' on
1316 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1317 * reported to mark messages seen on a TOP fetch.)
1319 * However...*don't* do this if we're using keep to suppress deletion!
1320 * In that case, marking the seen flag is the only way to prevent the
1321 * message from being re-fetched on subsequent runs.
1323 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1324 * This gives us a workaround for servers like usa.net's that bungle
1325 * TOP. It's pretty harmless because fetchall guarantees that any
1326 * message dropped by an interrupted RETR will be picked up on the
1327 * next poll of the site.
1329 * We take advantage here of the fact that, according to all the
1330 * POP RFCs, "if the number of lines requested by the POP3 client
1331 * is greater than than the number of lines in the body, then the
1332 * POP3 server sends the entire message.").
1334 * The line count passed (99999999) is the maximum value CompuServe will
1335 * accept; it's much lower than the natural value 2147483646 (the maximum
1336 * twos-complement signed 32-bit integer minus 1) */
1338 gen_send(sock, "RETR %d", number);
1340 gen_send(sock, "TOP %d 99999999", number);
1341 if ((ok = pop3_ok(sock, buf)) != 0)
1344 *lenp = -1; /* we got sizes from the LIST response */
1349 static void mark_uid_seen(struct query *ctl, int number)
1350 /* Tell the UID code we've seen this. */
1354 if ((sdp = id_find(&ctl->newsaved, number)))
1355 sdp->val.status.mark = UID_SEEN;
1356 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1357 * (say, due to socket error), the same mail will not be downloaded
1360 if ((sdp = id_find(&ctl->oldsaved, number)))
1361 sdp->val.status.mark = UID_SEEN;
1364 static int pop3_delete(int sock, struct query *ctl, int number)
1365 /* delete a given message */
1368 mark_uid_seen(ctl, number);
1369 /* actually, mark for deletion -- doesn't happen until QUIT time */
1370 ok = gen_transact(sock, "DELE %d", number);
1371 if (ok != PS_SUCCESS)
1373 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1377 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1378 /* mark a given message as seen */
1381 mark_uid_seen(ctl, number);
1385 static int pop3_logout(int sock, struct query *ctl)
1386 /* send logout command */
1392 * We used to do this in case the server marks messages deleted when seen.
1393 * (Yes, this has been reported, in the MercuryP/NLM server.
1394 * It's even legal under RFC 1939 (section 8) as a site policy.)
1395 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1396 * "Running 'fetchmail -F -v' and checking the logs, I found out
1397 * that fetchmail did in fact flush my mailbox properly, but sent
1398 * a RSET just before sending QUIT to log off. This caused the
1399 * POP3 server to undo/forget about the previous DELEs, resetting
1400 * my mailbox to its original (ie. unflushed) state. The
1401 * ~/.fetchids file did get flushed though, so the next time
1402 * fetchmail was run it saw all the old messages as new ones ..."
1405 gen_transact(sock, "RSET");
1406 #endif /* __UNUSED__ */
1408 ok = gen_transact(sock, "QUIT");
1415 static const struct method pop3 =
1417 "POP3", /* Post Office Protocol v3 */
1418 "pop3", /* port for plain and TLS POP3 */
1419 "pop3s", /* port for SSL POP3 */
1420 FALSE, /* this is not a tagged protocol */
1421 TRUE, /* this uses a message delimiter */
1422 pop3_ok, /* parse command response */
1423 pop3_getauth, /* get authorization */
1424 pop3_getrange, /* query range of messages */
1425 pop3_getsizes, /* we can get a list of sizes */
1426 pop3_getpartialsizes, /* we can get the size of 1 mail */
1427 pop3_is_old, /* how do we tell a message is old? */
1428 pop3_fetch, /* request given message */
1429 NULL, /* no way to fetch body alone */
1430 NULL, /* no message trailer */
1431 pop3_delete, /* how to delete a message */
1432 pop3_mark_seen, /* how to mark a message as seen */
1433 NULL, /* no action at end of mailbox */
1434 pop3_logout, /* log out, we're done */
1435 FALSE, /* no, we can't re-poll */
1438 int doPOP3 (struct query *ctl)
1439 /* retrieve messages using POP3 */
1442 if (ctl->mailboxes->id) {
1443 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1448 return(do_protocol(ctl, &pop3));
1450 #endif /* POP3_ENABLE */
1452 /* pop3.c ends here */