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() */
45 flag has_gssapi = FALSE;
46 #endif /* defined(GSSAPI) */
47 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
48 flag has_kerberos = FALSE;
49 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
50 static flag has_cram = FALSE;
53 #endif /* OPIE_ENABLE */
55 static flag has_stls = FALSE;
56 #endif /* SSL_ENABLE */
58 /* mailbox variables initialized in pop3_getrange() */
61 /* mail variables initialized in pop3_fetch() */
65 #endif /* SDPS_ENABLE */
71 * NTLM support by Grant Edwards.
73 * Handle MS-Exchange NTLM authentication method. This is the same
74 * as the NTLM auth used by Samba for SMB related services. We just
75 * encode the packets in base64 instead of sending them out via a
78 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
81 static int do_pop3_ntlm(int sock, struct query *ctl,
82 int msn_instead /** if true, send AUTH MSN, else send AUTH NTLM */)
84 tSmbNtlmAuthRequest request;
85 tSmbNtlmAuthChallenge challenge;
86 tSmbNtlmAuthResponse response;
91 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
93 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
99 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
101 if (outlevel >= O_DEBUG)
102 dumpSmbNtlmAuthRequest(stdout, &request);
104 memset(msgbuf,0,sizeof msgbuf);
105 to64frombits (msgbuf, &request, SmbLength(&request));
107 if (outlevel >= O_MONITOR)
108 report(stdout, "POP3> %s\n", msgbuf);
110 strcat(msgbuf,"\r\n");
111 SockWrite (sock, msgbuf, strlen (msgbuf));
113 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
116 len = from64tobits (&challenge, msgbuf, sizeof(msgbuf));
118 if (outlevel >= O_DEBUG)
119 dumpSmbNtlmAuthChallenge(stdout, &challenge);
121 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
123 if (outlevel >= O_DEBUG)
124 dumpSmbNtlmAuthResponse(stdout, &response);
126 memset(msgbuf,0,sizeof msgbuf);
127 to64frombits (msgbuf, &response, SmbLength(&response));
129 if (outlevel >= O_MONITOR)
130 report(stdout, "POP3> %s\n", msgbuf);
132 strcat(msgbuf,"\r\n");
133 SockWrite (sock, msgbuf, strlen (msgbuf));
135 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
138 if (strstr (msgbuf, "OK"))
146 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
148 static int pop3_ok (int sock, char *argbuf)
149 /* parse command response */
152 char buf [POPBUFSIZE+1];
155 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
157 if (*bufp == '+' || *bufp == '-')
162 while (isalpha((unsigned char)*bufp))
168 if (strcmp(buf,"+OK") == 0)
171 strcpy(lastok, bufp);
172 #endif /* OPIE_ENABLE */
175 else if (strncmp(buf,"-ERR", 4) == 0)
177 if (stage == STAGE_FETCH)
179 else if (stage > STAGE_GETAUTH)
182 * We're checking for "lock busy", "unable to lock",
183 * "already locked", "wait a few minutes" etc. here.
184 * This indicates that we have to wait for the server to
185 * unwedge itself before we can poll again.
187 * PS_LOCKBUSY check empirically verified with two recent
188 * versions of the Berkeley popper; QPOP (version 2.2) and
189 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
190 * These are caught by the case-indifferent "lock" check.
191 * The "wait" catches "mail storage services unavailable,
192 * wait a few minutes and try again" on the InterMail server.
194 * If these aren't picked up on correctly, fetchmail will
195 * think there is an authentication failure and wedge the
196 * connection in order to prevent futile polls.
200 else if (strstr(bufp,"lock")
201 || strstr(bufp,"Lock")
202 || strstr(bufp,"LOCK")
203 || strstr(bufp,"wait")
204 /* these are blessed by RFC 2449 */
205 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
207 else if ((strstr(bufp,"Service")
208 || strstr(bufp,"service"))
209 && (strstr(bufp,"unavailable")))
214 * We always want to pass the user lock-busy messages, because
215 * they're red flags. Other stuff (like AUTH failures on non-
216 * RFC1734 servers) only if we're debugging.
218 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
219 report(stderr, "%s\n", bufp);
224 #if POPBUFSIZE > MSGBUFSIZE
225 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
236 static int capa_probe(int sock)
237 /* probe the capabilities of the remote server */
243 #endif /* defined(GSSAPI) */
244 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
245 has_kerberos = FALSE;
246 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
250 #endif /* OPIE_ENABLE */
252 ok = gen_transact(sock, "CAPA");
253 if (ok == PS_SUCCESS)
257 /* determine what authentication methods we have available */
258 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
263 if (strstr(buffer, "STLS"))
265 #endif /* SSL_ENABLE */
267 if (strstr(buffer, "GSSAPI"))
269 #endif /* defined(GSSAPI) */
270 #if defined(KERBEROS_V4)
271 if (strstr(buffer, "KERBEROS_V4"))
273 #endif /* defined(KERBEROS_V4) */
275 if (strstr(buffer, "X-OTP"))
277 #endif /* OPIE_ENABLE */
278 if (strstr(buffer, "CRAM-MD5"))
285 static void set_peek_capable(struct query *ctl)
287 /* we're peek-capable means that the use of TOP is enabled,
288 * see pop3_fetch for details - short story, we can use TOP if
289 * we have a means of reliably tracking which mail we need to
290 * refetch should the connection abort in the middle.
291 * fetchall forces RETR, as does keep without UIDL */
292 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
295 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
296 /* apply for connection authorization */
303 #endif /* OPIE_ENABLE */
305 char *realhost = ctl->server.via ? ctl->server.via : ctl->server.pollname;
306 flag connection_may_have_tls_errors = FALSE;
307 #endif /* SSL_ENABLE */
311 #endif /* defined(GSSAPI) */
312 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
313 has_kerberos = FALSE;
314 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
318 #endif /* OPIE_ENABLE */
321 #endif /* SSL_ENABLE */
323 /* Set this up before authentication quits early. */
324 set_peek_capable(ctl);
326 * The "Maillennium POP3/PROXY server" deliberately truncates
327 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
328 * disable TOP. Comcast once spewed marketing babble to the extent
329 * of protecting Outlook -- pretty overzealous to break a protocol
330 * for that that Microsoft could have read, too. Comcast aren't
331 * alone in using this software though.
332 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
333 * (Thanks to Ed Wilts for reminding me of that.)
335 * The warning is printed once per server, until fetchmail exits.
336 * It will be suppressed when --fetchall or other circumstances make
337 * us use RETR anyhow.
341 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
342 if ((ctl->server.workarounds & WKA_TOP) == 0) {
343 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
344 ctl->server.workarounds |= WKA_TOP;
348 if (ctl->server.authenticate == A_SSH) {
354 * This needs to catch both demon.co.uk and demon.net.
355 * If we see either, and we're in multidrop mode, try to use
356 * the SDPS *ENV extension.
358 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
359 ctl->server.sdps = TRUE;
360 #endif /* SDPS_ENABLE */
363 /* MSN servers require the use of NTLM (MSN) authentication */
364 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
365 ctl->server.authenticate == A_MSN)
366 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
367 if (ctl->server.authenticate == A_NTLM)
368 return (do_pop3_ntlm(sock, ctl, 0) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
370 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
373 GT_("Required NTLM capability not compiled into fetchmail\n"));
377 switch (ctl->server.protocol) {
380 /* XXX FIXME: AUTH probing (RFC1734) should become global */
381 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
382 if (strstr(ctl->remotename, "@compuserve.com"))
384 /* AUTH command should return a list of available mechanisms */
385 if (gen_transact(sock, "AUTH") == 0)
388 flag has_rpa = FALSE;
390 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
394 if (strncasecmp(buffer, "rpa", 3) == 0)
397 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
398 ctl->password, sock))
404 #endif /* RPA_ENABLE */
407 * CAPA command may return a list including available
408 * authentication mechanisms. if it doesn't, no harm done, we
409 * just fall back to a plain login. Note that this code
410 * latches the server's authentication type, so that in daemon mode
411 * the CAPA check only needs to be done once at start of run.
413 * If CAPA fails, then force the authentication method to PASSORD
414 * and repoll immediately.
416 * These authentication methods are blessed by RFC1734,
417 * describing the POP3 AUTHentication command.
419 if ((ctl->server.authenticate == A_ANY) ||
420 (ctl->server.authenticate == A_GSSAPI) ||
421 (ctl->server.authenticate == A_KERBEROS_V4) ||
422 (ctl->server.authenticate == A_OTP) ||
423 (ctl->server.authenticate == A_CRAM_MD5))
425 if ((ok = capa_probe(sock)) != PS_SUCCESS)
426 /* we are in STAGE_GETAUTH! */
427 if (ok == PS_AUTHFAIL ||
428 /* Some servers directly close the socket. However, if we
429 * have already authenticated before, then a previous CAPA
430 * must have succeeded. In that case, treat this as a
431 * genuine socket error and do not change the auth method.
433 (ok == PS_SOCKET && !ctl->wehaveauthed))
435 ctl->server.authenticate = A_PASSWORD;
436 /* repoll immediately with PASS authentication */
445 /* opportunistic or forced TLS */
446 && (!ctl->sslproto || !strcasecmp(ctl->sslproto, "tls1")))
448 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
449 * protocol that will work with STARTTLS. Don't need to worry
450 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
452 if (gen_transact(sock, "STLS") == PS_SUCCESS
453 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
454 ctl->sslcertpath, ctl->sslfingerprint, realhost,
455 ctl->server.pollname, &ctl->remotename) != -1)
458 * RFC 2595 says this:
460 * "Once TLS has been started, the client MUST discard cached
461 * information about server capabilities and SHOULD re-issue the
462 * CAPABILITY command. This is necessary to protect against
463 * man-in-the-middle attacks which alter the capabilities list prior
464 * to STARTTLS. The server MAY advertise different capabilities
467 * Now that we're confident in our TLS connection we can
468 * guarantee a secure capability re-probe.
470 (void)capa_probe(sock);
471 if (outlevel >= O_VERBOSE)
473 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), realhost);
476 else if (ctl->sslfingerprint || ctl->sslcertck
477 || (ctl->sslproto && !strcasecmp(ctl->sslproto, "tls1")))
479 /* Config required TLS but we couldn't guarantee it, so we must
481 report(stderr, GT_("%s: upgrade to TLS failed.\n"), realhost);
486 /* We don't know whether the connection is usable, and there's
487 * no command we can reasonably issue to test it (NOOP isn't
488 * allowed til post-authentication), so leave it in an unknown
489 * state, mark it as such, and check more carefully if things
490 * go wrong when we try to authenticate. */
491 connection_may_have_tls_errors = TRUE;
492 if (outlevel >= O_VERBOSE)
494 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), realhost);
498 #endif /* SSL_ENABLE */
501 * OK, we have an authentication type now.
503 #if defined(KERBEROS_V4)
505 * Servers doing KPOP have to go through a dummy login sequence
506 * rather than doing SASL.
509 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
510 && (ctl->server.authenticate == A_KERBEROS_V4
511 || ctl->server.authenticate == A_KERBEROS_V5
512 || ctl->server.authenticate == A_ANY))
514 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
515 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
518 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
522 (ctl->server.authenticate == A_GSSAPI ||
523 ctl->server.authenticate == A_ANY))
525 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
526 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
529 #endif /* defined(GSSAPI) */
533 (ctl->server.authenticate == A_OTP ||
534 ctl->server.authenticate == A_ANY))
536 ok = do_otp(sock, "AUTH", ctl);
537 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
540 #endif /* OPIE_ENABLE */
542 if (ctl->server.authenticate == A_CRAM_MD5 ||
543 (has_cram && ctl->server.authenticate == A_ANY))
545 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
546 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
550 /* ordinary validation, no one-time password or RPA */
551 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
555 /* see RFC1938: A One-Time Password System */
556 if ((challenge = strstr(lastok, "otp-"))) {
557 char response[OPIE_RESPONSE_MAX+1];
559 char *n = xstrdup("");
561 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
563 if ((i == -2) && !run.poll_interval) {
564 char secret[OPIE_SECRET_MAX+1];
565 fprintf(stderr, GT_("Secret pass phrase: "));
566 if (opiereadpass(secret, sizeof(secret), 0))
567 i = opiegenerator(challenge, secret, response);
568 memset(secret, 0, sizeof(secret));
576 ok = gen_transact(sock, "PASS %s", response);
579 #endif /* OPIE_ENABLE */
581 strlcpy(shroud, ctl->password, sizeof(shroud));
582 ok = gen_transact(sock, "PASS %s", ctl->password);
585 /* this is for servers which claim to support TLS, but actually
587 if (connection_may_have_tls_errors && ok == PS_SOCKET)
589 ctl->sslproto = xstrdup("");
590 /* repoll immediately without TLS */
597 /* build MD5 digest from greeting timestamp + password */
598 /* find start of timestamp */
599 for (start = greeting; *start != 0 && *start != '<'; start++)
603 GT_("Required APOP timestamp not found in greeting\n"));
607 /* find end of timestamp */
608 for (end = start; *end != 0 && *end != '>'; end++)
610 if (*end == 0 || end == start + 1) {
612 GT_("Timestamp syntax error in greeting\n"));
618 /* copy timestamp and password into digestion buffer */
619 msg = xmalloc((end-start+1) + strlen(ctl->password) + 1);
621 strcat(msg,ctl->password);
622 strcpy(ctl->digest, MD5Digest((unsigned char *)msg));
625 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, ctl->digest);
629 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0)
630 ok = gen_transact(sock, "RPOP %s", ctl->password);
634 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
640 /* maybe we detected a lock-busy condition? */
641 if (ok == PS_LOCKBUSY)
642 report(stderr, GT_("lock busy! Is another session active?\n"));
647 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
648 * accepted by Matthias Andree.
650 * Rationale: the server must have locked the spool before returning +OK;
651 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
654 * Empirical experience shows some server/OS combinations
655 * may need a brief pause even after any lockfiles on the
656 * server are released, to give the server time to finish
657 * copying back very large mailfolders from the temp-file...
658 * this is only ever an issue with extremely large mailboxes.
660 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
667 /* cut off C string at first POSIX space */
668 static void trim(char *s) {
669 s += strcspn(s, POSIX_space);
673 /* XXX FIXME: using the Message-ID is unsafe, some messages (spam,
674 * broken messages) do not have Message-ID headers, and messages without
675 * those appear to break this code and cause fetchmail (at least version
676 * 6.2.3) to not delete such messages properly after retrieval.
677 * See Sourceforge Bug #780933.
679 * The other problem is that the TOP command itself is optional, too... */
680 static int pop3_gettopid(int sock, int num , char *id, size_t idsize)
684 char buf [POPBUFSIZE+1];
685 snprintf(buf, sizeof(buf), "TOP %d 1", num);
686 if ((ok = gen_transact(sock, buf )) != 0)
689 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
693 if (!got_it && 0 == strncasecmp("Message-Id:", buf, 11)) {
696 p += strspn(p, POSIX_space);
697 strlcpy(id, p, idsize);
701 /* XXX FIXME: do not return success here if no Message-ID header was
706 /** Parse the UID response (leading +OK must have been
707 * stripped off) in buf, store the number in gotnum, and store the ID
708 * into the caller-provided buffer "id" of size "idsize".
709 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
710 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
715 /* skip leading blanks ourselves */
717 i += strspn(i, POSIX_space);
719 *gotnum = strtoul(i, &j, 10);
720 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
721 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
724 j += strspn(j, POSIX_space);
725 strlcpy(id, j, idsize);
730 /** request UIDL for single message \a num and stuff the result into the
731 * buffer \a id which can hold \a idsize bytes */
732 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
735 char buf [POPBUFSIZE+1];
736 unsigned long gotnum;
738 gen_send(sock, "UIDL %d", num);
739 if ((ok = pop3_ok(sock, buf)) != 0)
741 if ((ok = parseuid(buf, &gotnum, id, idsize)))
743 if (gotnum != (unsigned long)num) {
744 report(stderr, GT_("Server responded with UID for wrong message.\n"));
750 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
753 unsigned int first_nr, last_nr, try_nr;
758 while (first_nr < last_nr - 1)
762 try_nr = (first_nr + last_nr) / 2;
763 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
765 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
767 flag mark = newl->val.status.mark;
768 if (mark == UID_DELETED || mark == UID_EXPUNGED)
770 if (outlevel >= O_VERBOSE)
771 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, try_nr);
772 /* just mark it as seen now! */
773 newl->val.status.mark = mark = UID_SEEN;
776 /* narrow the search region! */
777 if (mark == UID_UNSEEN)
779 if (outlevel >= O_DEBUG)
780 report(stdout, GT_("%u is unseen\n"), try_nr);
786 /* save the number */
787 newl->val.status.num = try_nr;
791 if (outlevel >= O_DEBUG)
792 report(stdout, GT_("%u is unseen\n"), try_nr);
796 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
797 newl->val.status.num = try_nr;
800 if (outlevel >= O_DEBUG && last_nr <= count)
801 report(stdout, GT_("%u is first unseen\n"), last_nr);
804 *newp = count - first_nr;
809 static int pop3_slowuidl( int sock, struct query *ctl, int *countp, int *newp)
811 /* XXX FIXME: this code is severely broken. A Cc:d mailing list
812 * message will arrive twice with the same Message-ID, so this
813 * slowuidl code will break. Same goes for messages without
814 * Message-ID headers at all. This code would best be removed. */
815 /* This approach tries to get the message headers from the
816 * remote hosts and compares the message-id to the already known
818 * + if the first message containes a new id, all messages on
819 * the server will be new
820 * + if the first is known, try to estimate the last known message
821 * on the server and check. If this works you know the total number
822 * of messages to get.
823 * + Otherwise run a binary search to determine the last known message
825 int ok, nolinear = 0;
826 int first_nr, list_len, try_id, try_nr, add_id;
830 if ((ok = pop3_gettopid(sock, 1, id, sizeof(id))) != 0)
833 if( ( first_nr = str_nr_in_list(&ctl->oldsaved, id) ) == -1 ) {
834 /* the first message is unknown -> all messages are new */
839 /* check where we expect the latest known message */
840 list_len = count_list( &ctl->oldsaved );
841 try_id = list_len - first_nr; /* -1 + 1 */
843 if( try_id <= *countp ) {
844 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
847 try_nr = str_nr_last_in_list(&ctl->oldsaved, id);
852 if( try_nr != list_len -1 ) {
853 /* some messages inbetween have been deleted... */
857 for( add_id = 1<<30; add_id > try_id-1; add_id >>= 1 )
859 for( ; add_id; add_id >>= 1 ) {
861 if( try_id - add_id <= 1 ) {
868 if ((ok = pop3_gettopid(sock, try_id, id, sizeof(id))) != 0)
870 try_nr = str_nr_in_list(&ctl->oldsaved, id);
877 GT_("Messages inserted into list on server. Cannot handle this.\n"));
882 /* the first try_id messages are known -> copy them to the newsaved list */
883 for( num = first_nr; num < list_len; num++ )
885 struct idlist *newl = save_str(&ctl->newsaved,
886 str_from_nr_list(&ctl->oldsaved, num),
888 newl->val.status.num = num - first_nr + 1;
892 free_str_list(&ctl->oldsaved);
897 *newp = *countp - try_id;
901 static int pop3_getrange(int sock,
904 int *countp, int *newp, int *bytes)
905 /* get range of messages to be fetched */
908 char buf [POPBUFSIZE+1];
911 /* Ensure that the new list is properly empty */
912 ctl->newsaved = (struct idlist *)NULL;
915 /* Alain Knaff suggests this, but it's not RFC standard */
917 if ((ok = gen_transact(sock, "MBOX %s", folder)))
921 /* get the total message count */
922 gen_send(sock, "STAT");
923 ok = pop3_ok(sock, buf);
925 sscanf(buf,"%d %d", countp, bytes);
930 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
931 * command. We work as hard as possible to hide this, but it makes
932 * counting new messages intrinsically quadratic in the worst case.
936 /* if there are messages, and UIDL is desired, use UIDL
937 * also use UIDL if fetchall is unset */
938 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
943 /* should we do fast uidl this time? */
944 fastuidl = ctl->fastuidl;
945 if (*countp > 7 && /* linear search is better if there are few mails! */
946 !ctl->fetchall && /* with fetchall, all uids are required */
947 !ctl->flush && /* with flush, it is safer to disable fastuidl */
948 NUM_NONZERO (fastuidl))
953 dofastuidl = ctl->fastuidlcount != 0;
958 if (!ctl->server.uidl) {
959 gen_send(sock, "LAST");
960 ok = pop3_ok(sock, buf);
966 /* scan LAST reply */
967 if (sscanf(buf, "%d", &last) == 0)
969 report(stderr, GT_("protocol error\n"));
972 *newp = (*countp - last);
978 return(pop3_fastuidl( sock, ctl, *countp, newp));
979 /* grab the mailbox's UID list */
980 if ((ok = gen_transact(sock, "UIDL")) != 0)
982 /* don't worry, yet! do it the slow way */
983 if ((ok = pop3_slowuidl(sock, ctl, countp, newp)))
985 report(stderr, GT_("protocol error while fetching UIDLs\n"));
991 /* UIDL worked - parse reply */
995 while ((ok = gen_recv(sock, buf, sizeof(buf))) == PS_SUCCESS)
1000 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
1002 struct idlist *old, *newl;
1004 newl = save_str(&ctl->newsaved, id, UID_UNSEEN);
1005 newl->val.status.num = unum;
1007 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
1009 flag mark = old->val.status.mark;
1010 if (mark == UID_DELETED || mark == UID_EXPUNGED)
1012 /* XXX FIXME: switch 3 occurrences from
1013 * (int)unum or (unsigned int)unum to
1014 * remove the cast and use %lu - not now
1015 * though, time for new release */
1016 if (outlevel >= O_VERBOSE)
1017 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
1018 /* just mark it as seen now! */
1019 old->val.status.mark = mark = UID_SEEN;
1021 newl->val.status.mark = mark;
1022 if (mark == UID_UNSEEN)
1025 if (outlevel >= O_DEBUG)
1026 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1032 if (outlevel >= O_DEBUG)
1033 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
1034 /* add it to oldsaved also! In case, we do not
1035 * swap the lists (say, due to socket error),
1036 * the same mail will not be downloaded again.
1038 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1040 /* save the number */
1041 old->val.status.num = unum;
1044 } /* multi-line loop for UIDL reply */
1052 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
1053 /* capture the size of message #first */
1056 char buf [POPBUFSIZE+1];
1059 for (i = first; i <= last; i++) {
1060 gen_send(sock, "LIST %d", i);
1061 if ((ok = pop3_ok(sock, buf)) != 0)
1063 if (sscanf(buf, "%d %u", &num, &size) == 2) {
1065 sizes[i - first] = size;
1067 /* warn about possible attempt to induce buffer overrun
1069 * we expect server reply message number and requested
1070 * message number to match */
1071 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1077 static int pop3_getsizes(int sock, int count, int *sizes)
1078 /* capture the sizes of all messages */
1082 if ((ok = gen_transact(sock, "LIST")) != 0)
1086 char buf [POPBUFSIZE+1];
1088 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1090 unsigned int num, size;
1094 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1095 if (num > 0 && num <= (unsigned)count)
1096 sizes[num - 1] = size;
1098 /* warn about possible attempt to induce buffer overrun */
1099 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1107 static int pop3_is_old(int sock, struct query *ctl, int num)
1108 /* is the given message old? */
1110 struct idlist *newl;
1112 return (num <= last);
1113 else if (dofastuidl)
1120 /* in fast uidl, we manipulate the old list only! */
1122 if ((newl = id_find(&ctl->oldsaved, num)))
1124 /* we already have the id! */
1125 return(newl->val.status.mark != UID_UNSEEN);
1128 /* get the uidl first! */
1129 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1132 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1133 /* we already have the id! */
1134 newl->val.status.num = num;
1135 return(newl->val.status.mark != UID_UNSEEN);
1139 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1140 newl->val.status.num = num;
1144 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1145 newl->val.status.mark != UID_UNSEEN);
1150 * We could use this to fetch headers only as we do for IMAP. The trouble
1151 * is that there's no way to fetch the body only. So the following RETR
1152 * would have to re-fetch the header. Enough messages have longer headers
1153 * than bodies to make this a net loss.
1155 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1156 /* request headers of nth message */
1159 char buf[POPBUFSIZE+1];
1161 gen_send(sock, "TOP %d 0", number);
1162 if ((ok = pop3_ok(sock, buf)) != 0)
1165 *lenp = -1; /* we got sizes from the LIST response */
1171 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1172 /* request nth message */
1175 char buf[POPBUFSIZE+1];
1179 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1180 * for a description of what we're parsing here.
1181 * -- updated 2006-02-22
1183 if (ctl->server.sdps)
1187 sdps_envfrom = (char *)NULL;
1188 sdps_envto = (char *)NULL;
1189 gen_send(sock, "*ENV %d", number);
1191 if (gen_recv(sock, buf, sizeof(buf)))
1196 switch (linecount) {
1198 /* No need to wrap envelope from address */
1199 /* FIXME: some parts of fetchmail don't handle null
1200 * envelope senders, so use <> to mark null sender
1201 * as a workaround. */
1202 if (strspn(buf, " \t") == strlen(buf))
1204 sdps_envfrom = xmalloc(strlen(buf)+1);
1205 strcpy(sdps_envfrom,buf);
1208 /* Wrap address with To: <> so nxtaddr() likes it */
1209 sdps_envto = xmalloc(strlen(buf)+7);
1210 sprintf(sdps_envto,"To: <%s>",buf);
1214 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1218 #endif /* SDPS_ENABLE */
1221 * Though the POP RFCs don't document this fact, on almost every
1222 * POP3 server I know of messages are marked "seen" only at the
1223 * time the OK response to a RETR is issued.
1225 * This means we can use TOP to fetch the message without setting its
1226 * seen flag. This is good! It means that if the protocol exchange
1227 * craps out during the message, it will still be marked `unseen' on
1228 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1229 * reported to mark messages seen on a TOP fetch.)
1231 * However...*don't* do this if we're using keep to suppress deletion!
1232 * In that case, marking the seen flag is the only way to prevent the
1233 * message from being re-fetched on subsequent runs.
1235 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1236 * This gives us a workaround for servers like usa.net's that bungle
1237 * TOP. It's pretty harmless because fetchall guarantees that any
1238 * message dropped by an interrupted RETR will be picked up on the
1239 * next poll of the site.
1241 * We take advantage here of the fact that, according to all the
1242 * POP RFCs, "if the number of lines requested by the POP3 client
1243 * is greater than than the number of lines in the body, then the
1244 * POP3 server sends the entire message.").
1246 * The line count passed (99999999) is the maximum value CompuServe will
1247 * accept; it's much lower than the natural value 2147483646 (the maximum
1248 * twos-complement signed 32-bit integer minus 1) */
1250 gen_send(sock, "RETR %d", number);
1252 gen_send(sock, "TOP %d 99999999", number);
1253 if ((ok = pop3_ok(sock, buf)) != 0)
1256 *lenp = -1; /* we got sizes from the LIST response */
1261 static void mark_uid_seen(struct query *ctl, int number)
1262 /* Tell the UID code we've seen this. */
1266 if ((sdp = id_find(&ctl->newsaved, number)))
1267 sdp->val.status.mark = UID_SEEN;
1268 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1269 * (say, due to socket error), the same mail will not be downloaded
1272 if ((sdp = id_find(&ctl->oldsaved, number)))
1273 sdp->val.status.mark = UID_SEEN;
1276 static int pop3_delete(int sock, struct query *ctl, int number)
1277 /* delete a given message */
1280 mark_uid_seen(ctl, number);
1281 /* actually, mark for deletion -- doesn't happen until QUIT time */
1282 ok = gen_transact(sock, "DELE %d", number);
1283 if (ok != PS_SUCCESS)
1285 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1289 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1290 /* mark a given message as seen */
1293 mark_uid_seen(ctl, number);
1297 static int pop3_logout(int sock, struct query *ctl)
1298 /* send logout command */
1304 * We used to do this in case the server marks messages deleted when seen.
1305 * (Yes, this has been reported, in the MercuryP/NLM server.
1306 * It's even legal under RFC 1939 (section 8) as a site policy.)
1307 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1308 * "Running 'fetchmail -F -v' and checking the logs, I found out
1309 * that fetchmail did in fact flush my mailbox properly, but sent
1310 * a RSET just before sending QUIT to log off. This caused the
1311 * POP3 server to undo/forget about the previous DELEs, resetting
1312 * my mailbox to its original (ie. unflushed) state. The
1313 * ~/.fetchids file did get flushed though, so the next time
1314 * fetchmail was run it saw all the old messages as new ones ..."
1317 gen_transact(sock, "RSET");
1318 #endif /* __UNUSED__ */
1320 ok = gen_transact(sock, "QUIT");
1327 static const struct method pop3 =
1329 "POP3", /* Post Office Protocol v3 */
1330 "pop3", /* port for plain and TLS POP3 */
1331 "pop3s", /* port for SSL POP3 */
1332 FALSE, /* this is not a tagged protocol */
1333 TRUE, /* this uses a message delimiter */
1334 pop3_ok, /* parse command response */
1335 pop3_getauth, /* get authorization */
1336 pop3_getrange, /* query range of messages */
1337 pop3_getsizes, /* we can get a list of sizes */
1338 pop3_getpartialsizes, /* we can get the size of 1 mail */
1339 pop3_is_old, /* how do we tell a message is old? */
1340 pop3_fetch, /* request given message */
1341 NULL, /* no way to fetch body alone */
1342 NULL, /* no message trailer */
1343 pop3_delete, /* how to delete a message */
1344 pop3_mark_seen, /* how to mark a message as seen */
1345 NULL, /* no action at end of mailbox */
1346 pop3_logout, /* log out, we're done */
1347 FALSE, /* no, we can't re-poll */
1350 int doPOP3 (struct query *ctl)
1351 /* retrieve messages using POP3 */
1354 if (ctl->mailboxes->id) {
1355 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1360 return(do_protocol(ctl, &pop3));
1362 #endif /* POP3_ENABLE */
1364 /* pop3.c ends here */