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 && (!ctl->keep || ctl->server.uidl);
265 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
266 /* apply for connection authorization */
273 #endif /* OPIE_ENABLE */
275 flag connection_may_have_tls_errors = FALSE;
276 #endif /* SSL_ENABLE */
281 #endif /* defined(GSSAPI) */
282 #if defined(KERBEROS_V5)
283 has_kerberos = FALSE;
284 #endif /* defined(KERBEROS_V5) */
288 #endif /* OPIE_ENABLE */
291 #endif /* SSL_ENABLE */
293 /* Set this up before authentication quits early. */
294 set_peek_capable(ctl);
296 /* Hack: allow user to force RETR. */
297 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
302 * The "Maillennium POP3/PROXY server" deliberately truncates
303 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
304 * disable TOP. Comcast once spewed marketing babble to the extent
305 * of protecting Outlook -- pretty overzealous to break a protocol
306 * for that that Microsoft could have read, too. Comcast aren't
307 * alone in using this software though.
308 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
309 * (Thanks to Ed Wilts for reminding me of that.)
311 * The warning is printed once per server, until fetchmail exits.
312 * It will be suppressed when --fetchall or other circumstances make
313 * us use RETR anyhow.
317 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
318 if ((ctl->server.workarounds & WKA_TOP) == 0) {
319 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
320 ctl->server.workarounds |= WKA_TOP;
324 if (ctl->server.authenticate == A_SSH) {
330 * This needs to catch both demon.co.uk and demon.net.
331 * If we see either, and we're in multidrop mode, try to use
332 * the SDPS *ENV extension.
334 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
335 ctl->server.sdps = TRUE;
336 #endif /* SDPS_ENABLE */
338 switch (ctl->server.protocol) {
341 /* XXX FIXME: AUTH probing (RFC1734) should become global */
342 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
343 if (strstr(ctl->remotename, "@compuserve.com"))
345 /* AUTH command should return a list of available mechanisms */
346 if (gen_transact(sock, "AUTH") == 0)
349 flag has_rpa = FALSE;
351 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
355 if (strncasecmp(buffer, "rpa", 3) == 0)
358 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
359 ctl->password, sock))
365 #endif /* RPA_ENABLE */
368 * CAPA command may return a list including available
369 * authentication mechanisms and STLS capability.
371 * If it doesn't, no harm done, we just fall back to a plain
372 * login -- if the user allows it.
374 * Note that this code latches the server's authentication type,
375 * so that in daemon mode the CAPA check only needs to be done
376 * once at start of run.
378 * If CAPA fails, then force the authentication method to
379 * PASSWORD, switch off opportunistic and repoll immediately.
380 * If TLS is mandatory, fail up front.
382 if ((ctl->server.authenticate == A_ANY) ||
383 (ctl->server.authenticate == A_GSSAPI) ||
384 (ctl->server.authenticate == A_KERBEROS_V5) ||
385 (ctl->server.authenticate == A_OTP) ||
386 (ctl->server.authenticate == A_CRAM_MD5) ||
389 if ((ok = capa_probe(sock)) != PS_SUCCESS)
390 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
391 if (ok == PS_AUTHFAIL ||
392 /* Some servers directly close the socket. However, if we
393 * have already authenticated before, then a previous CAPA
394 * must have succeeded. In that case, treat this as a
395 * genuine socket error and do not change the auth method.
397 (ok == PS_SOCKET && !ctl->wehaveauthed))
401 /* fail with mandatory STLS without repoll */
402 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
403 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
405 } else if (maybe_tls(ctl)) {
406 /* defeat opportunistic STLS */
407 xfree(ctl->sslproto);
408 ctl->sslproto = xstrdup("");
411 /* If strong authentication was opportunistic, retry without, else fail. */
412 switch (ctl->server.authenticate) {
414 ctl->server.authenticate = A_PASSWORD;
416 case A_PASSWORD: /* this should only happen with TLS enabled */
425 if (maybe_tls(ctl)) {
428 commonname = ctl->server.pollname;
430 commonname = ctl->server.via;
431 if (ctl->sslcommonname)
432 commonname = ctl->sslcommonname;
435 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
437 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
438 * protocol that will work with STARTTLS. Don't need to worry
439 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
441 if (gen_transact(sock, "STLS") == PS_SUCCESS
442 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
443 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
444 ctl->server.pollname, &ctl->remotename) != -1)
447 * RFC 2595 says this:
449 * "Once TLS has been started, the client MUST discard cached
450 * information about server capabilities and SHOULD re-issue the
451 * CAPABILITY command. This is necessary to protect against
452 * man-in-the-middle attacks which alter the capabilities list prior
453 * to STARTTLS. The server MAY advertise different capabilities
456 * Now that we're confident in our TLS connection we can
457 * guarantee a secure capability re-probe.
460 ok = capa_probe(sock);
461 if (ok != PS_SUCCESS) {
464 if (outlevel >= O_VERBOSE)
466 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
468 } else if (must_tls(ctl)) {
469 /* Config required TLS but we couldn't guarantee it, so we must
471 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
474 /* We don't know whether the connection is usable, and there's
475 * no command we can reasonably issue to test it (NOOP isn't
476 * allowed til post-authentication), so leave it in an unknown
477 * state, mark it as such, and check more carefully if things
478 * go wrong when we try to authenticate. */
479 connection_may_have_tls_errors = TRUE;
480 if (outlevel >= O_VERBOSE)
482 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
487 #endif /* SSL_ENABLE */
490 * OK, we have an authentication type now.
495 (ctl->server.authenticate == A_GSSAPI ||
496 (ctl->server.authenticate == A_ANY
497 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
499 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
500 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
503 #endif /* defined(GSSAPI) */
507 (ctl->server.authenticate == A_OTP ||
508 ctl->server.authenticate == A_ANY))
510 ok = do_otp(sock, "AUTH", ctl);
511 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
514 #endif /* OPIE_ENABLE */
517 /* MSN servers require the use of NTLM (MSN) authentication */
518 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
519 ctl->server.authenticate == A_MSN)
520 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
521 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
522 ok = do_pop3_ntlm(sock, ctl, 0);
523 if (ok == 0 || ctl->server.authenticate != A_ANY)
527 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
530 GT_("Required NTLM capability not compiled into fetchmail\n"));
534 if (ctl->server.authenticate == A_CRAM_MD5 ||
535 (has_cram && ctl->server.authenticate == A_ANY))
537 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
538 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
542 /* ordinary validation, no one-time password or RPA */
543 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
547 /* see RFC1938: A One-Time Password System */
548 if ((challenge = strstr(lastok, "otp-"))) {
549 char response[OPIE_RESPONSE_MAX+1];
551 char *n = xstrdup("");
553 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
555 if ((i == -2) && !run.poll_interval) {
556 char secret[OPIE_SECRET_MAX+1];
557 fprintf(stderr, GT_("Secret pass phrase: "));
558 if (opiereadpass(secret, sizeof(secret), 0))
559 i = opiegenerator(challenge, secret, response);
560 memset(secret, 0, sizeof(secret));
568 ok = gen_transact(sock, "PASS %s", response);
571 #endif /* OPIE_ENABLE */
573 /* KPOP uses out-of-band authentication and does not check what
574 * we send here, so send some random fixed string, to avoid
575 * users switching *to* KPOP accidentally revealing their
577 if ((ctl->server.authenticate == A_ANY
578 || ctl->server.authenticate == A_KERBEROS_V5)
579 && (ctl->server.service != NULL
580 && strcmp(ctl->server.service, KPOP_PORT) == 0))
582 ok = gen_transact(sock, "PASS krb_ticket");
586 /* check if we are actually allowed to send the password */
587 if (ctl->server.authenticate == A_ANY
588 || ctl->server.authenticate == A_PASSWORD) {
589 strlcpy(shroud, ctl->password, sizeof(shroud));
590 ok = gen_transact(sock, "PASS %s", ctl->password);
592 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
595 memset(shroud, 0x55, sizeof(shroud));
600 /* build MD5 digest from greeting timestamp + password */
601 /* find start of timestamp */
602 for (start = greeting; *start != 0 && *start != '<'; start++)
606 GT_("Required APOP timestamp not found in greeting\n"));
610 /* find end of timestamp */
611 for (end = start; *end != 0 && *end != '>'; end++)
613 if (*end == 0 || end == start + 1) {
615 GT_("Timestamp syntax error in greeting\n"));
621 /* SECURITY: 2007-03-17
622 * Strictly validating the presented challenge for RFC-822
623 * conformity (it must be a msg-id in terms of that standard) is
624 * supposed to make attacks against the MD5 implementation
627 * [1] "Security vulnerability in APOP authentication",
628 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
629 if (!rfc822_valid_msgid((unsigned char *)start)) {
631 GT_("Invalid APOP timestamp.\n"));
635 /* copy timestamp and password into digestion buffer */
636 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
638 strcat(msg,ctl->password);
639 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
642 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
646 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
651 /* this is for servers which claim to support TLS, but actually
653 if (connection_may_have_tls_errors
654 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
656 xfree(ctl->sslproto);
657 ctl->sslproto = xstrdup("");
658 /* repoll immediately without TLS */
665 /* maybe we detected a lock-busy condition? */
666 if (ok == PS_LOCKBUSY)
667 report(stderr, GT_("lock busy! Is another session active?\n"));
672 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
673 * accepted by Matthias Andree.
675 * Rationale: the server must have locked the spool before returning +OK;
676 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
679 * Empirical experience shows some server/OS combinations
680 * may need a brief pause even after any lockfiles on the
681 * server are released, to give the server time to finish
682 * copying back very large mailfolders from the temp-file...
683 * this is only ever an issue with extremely large mailboxes.
685 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
692 /* cut off C string at first POSIX space */
693 static void trim(char *s) {
694 s += strcspn(s, POSIX_space);
698 /** Parse the UID response (leading +OK must have been
699 * stripped off) in buf, store the number in gotnum, and store the ID
700 * into the caller-provided buffer "id" of size "idsize".
701 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
702 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
707 /* skip leading blanks ourselves */
709 i += strspn(i, POSIX_space);
711 *gotnum = strtoul(i, &j, 10);
712 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
713 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
716 j += strspn(j, POSIX_space);
717 strlcpy(id, j, idsize);
722 /** request UIDL for single message \a num and stuff the result into the
723 * buffer \a id which can hold \a idsize bytes */
724 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
727 char buf [POPBUFSIZE+1];
728 unsigned long gotnum;
730 gen_send(sock, "UIDL %d", num);
731 if ((ok = pop3_ok(sock, buf)) != 0)
733 if ((ok = parseuid(buf, &gotnum, id, idsize)))
735 if (gotnum != (unsigned long)num) {
736 report(stderr, GT_("Server responded with UID for wrong message.\n"));
742 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
745 unsigned int first_nr, last_nr, try_nr;
750 while (first_nr < last_nr - 1)
752 struct uid_db_record *rec;
754 try_nr = (first_nr + last_nr) / 2;
755 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
757 if ((rec = find_uid_by_id(&ctl->oldsaved, id)))
759 flag mark = rec->status;
760 if (mark == UID_DELETED || mark == UID_EXPUNGED)
762 if (outlevel >= O_VERBOSE)
763 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
764 /* just mark it as seen now! */
765 rec->status = mark = UID_SEEN;
768 /* narrow the search region! */
769 if (mark == UID_UNSEEN)
771 if (outlevel >= O_DEBUG)
772 report(stdout, GT_("%u is unseen\n"), try_nr);
778 /* save the number */
779 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
783 if (outlevel >= O_DEBUG)
784 report(stdout, GT_("%u is unseen\n"), try_nr);
788 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
789 set_uid_db_num(&ctl->oldsaved, rec, try_nr);
792 if (outlevel >= O_DEBUG && last_nr <= count)
793 report(stdout, GT_("%u is first unseen\n"), last_nr);
796 *newp = count - first_nr;
801 static int pop3_getrange(int sock,
804 int *countp, int *newp, int *bytes)
805 /* get range of messages to be fetched */
808 char buf [POPBUFSIZE+1];
811 /* Ensure that the new list is properly empty */
812 clear_uid_db(&ctl->newsaved);
815 /* Alain Knaff suggests this, but it's not RFC standard */
817 if ((ok = gen_transact(sock, "MBOX %s", folder)))
821 /* get the total message count */
822 gen_send(sock, "STAT");
823 ok = pop3_ok(sock, buf);
827 asgn = sscanf(buf,"%d %d", countp, bytes);
834 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
835 * command. We work as hard as possible to hide this, but it makes
836 * counting new messages intrinsically quadratic in the worst case.
840 /* if there are messages, and UIDL is desired, use UIDL
841 * also use UIDL if fetchall is unset */
842 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
847 set_uid_db_num_pos_0(&ctl->oldsaved, *countp);
848 set_uid_db_num_pos_0(&ctl->newsaved, *countp);
850 /* should we do fast uidl this time? */
851 fastuidl = ctl->fastuidl;
852 if (*countp > 7 && /* linear search is better if there are few mails! */
853 !ctl->fetchall && /* with fetchall, all uids are required */
854 !ctl->flush && /* with flush, it is safer to disable fastuidl */
855 NUM_NONZERO (fastuidl))
860 dofastuidl = ctl->fastuidlcount != 0;
865 if (!ctl->server.uidl) {
866 gen_send(sock, "LAST");
867 ok = pop3_ok(sock, buf);
873 /* scan LAST reply */
874 if (sscanf(buf, "%d", &last) == 0)
876 report(stderr, GT_("protocol error\n"));
879 *newp = (*countp - last);
885 return(pop3_fastuidl( sock, ctl, *countp, newp));
886 /* grab the mailbox's UID list */
887 if (gen_transact(sock, "UIDL") != 0)
889 report(stderr, GT_("protocol error while fetching UIDLs\n"));
894 /* UIDL worked - parse reply */
898 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
903 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
905 struct uid_db_record *old_rec, *new_rec;
907 new_rec = uid_db_insert(&ctl->newsaved, id, UID_UNSEEN);
909 if ((old_rec = find_uid_by_id(&ctl->oldsaved, id)))
911 flag mark = old_rec->status;
912 if (mark == UID_DELETED || mark == UID_EXPUNGED)
914 /* XXX FIXME: switch 3 occurrences from
915 * (int)unum or (unsigned int)unum to
916 * remove the cast and use %lu - not now
917 * though, time for new release */
918 if (outlevel >= O_VERBOSE)
919 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
920 /* just mark it as seen now! */
921 old_rec->status = mark = UID_SEEN;
923 new_rec->status = mark;
924 if (mark == UID_UNSEEN)
927 if (outlevel >= O_DEBUG)
928 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
934 if (outlevel >= O_DEBUG)
935 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
936 /* add it to oldsaved also! In case, we do not
937 * swap the lists (say, due to socket error),
938 * the same mail will not be downloaded again.
940 old_rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
943 /* save the number */
944 if (new_rec->status == UID_UNSEEN || !ctl->keep) {
945 set_uid_db_num(&ctl->oldsaved, old_rec, unum);
946 set_uid_db_num(&ctl->newsaved, new_rec, unum);
950 } /* multi-line loop for UIDL reply */
958 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
959 /* capture the size of message #first */
962 char buf [POPBUFSIZE+1];
965 for (i = first; i <= last; i++) {
966 gen_send(sock, "LIST %d", i);
967 if ((ok = pop3_ok(sock, buf)) != 0)
969 if (sscanf(buf, "%d %u", &num, &size) == 2) {
971 sizes[i - first] = size;
973 /* warn about possible attempt to induce buffer overrun
975 * we expect server reply message number and requested
976 * message number to match */
977 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
983 static int pop3_getsizes(int sock, int count, int *sizes)
984 /* capture the sizes of all messages */
988 if ((ok = gen_transact(sock, "LIST")) != 0)
992 char buf [POPBUFSIZE+1];
994 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
996 unsigned int num, size;
1000 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1001 if (num > 0 && num <= (unsigned)count)
1002 sizes[num - 1] = size;
1004 /* warn about possible attempt to induce buffer overrun */
1005 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1013 static int pop3_is_old(int sock, struct query *ctl, int num)
1014 /* is the given message old? */
1016 struct uid_db_record *rec;
1018 if (!uid_db_n_records(&ctl->oldsaved))
1019 return (num <= last);
1020 else if (dofastuidl)
1027 /* in fast uidl, we manipulate the old list only! */
1029 if ((rec = find_uid_by_num(&ctl->oldsaved, num)))
1031 /* we already have the id! */
1032 return(rec->status != UID_UNSEEN);
1035 /* get the uidl first! */
1036 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1039 if ((rec = find_uid_by_id(&ctl->oldsaved, id))) {
1040 /* we already have the id! */
1041 set_uid_db_num(&ctl->oldsaved, rec, num);
1042 return(rec->status != UID_UNSEEN);
1046 rec = uid_db_insert(&ctl->oldsaved, id, UID_UNSEEN);
1047 set_uid_db_num(&ctl->oldsaved, rec, num);
1051 rec = find_uid_by_num(&ctl->newsaved, num);
1052 return !rec || rec->status != UID_UNSEEN;
1056 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1057 /* request nth message */
1060 char buf[POPBUFSIZE+1];
1064 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1065 * for a description of what we're parsing here.
1066 * -- updated 2006-02-22
1068 if (ctl->server.sdps)
1072 sdps_envfrom = (char *)NULL;
1073 sdps_envto = (char *)NULL;
1074 gen_send(sock, "*ENV %d", number);
1076 if (gen_recv(sock, buf, sizeof(buf)))
1081 switch (linecount) {
1083 /* No need to wrap envelope from address */
1084 /* FIXME: some parts of fetchmail don't handle null
1085 * envelope senders, so use <> to mark null sender
1086 * as a workaround. */
1087 if (strspn(buf, " \t") == strlen(buf))
1089 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1090 strcpy(sdps_envfrom,buf);
1093 /* Wrap address with To: <> so nxtaddr() likes it */
1094 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1095 sprintf(sdps_envto,"To: <%s>",buf);
1099 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1103 #endif /* SDPS_ENABLE */
1106 * Though the POP RFCs don't document this fact, on almost every
1107 * POP3 server I know of messages are marked "seen" only at the
1108 * time the OK response to a RETR is issued.
1110 * This means we can use TOP to fetch the message without setting its
1111 * seen flag. This is good! It means that if the protocol exchange
1112 * craps out during the message, it will still be marked `unseen' on
1113 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1114 * reported to mark messages seen on a TOP fetch.)
1116 * However...*don't* do this if we're using keep to suppress deletion!
1117 * In that case, marking the seen flag is the only way to prevent the
1118 * message from being re-fetched on subsequent runs.
1120 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1121 * This gives us a workaround for servers like usa.net's that bungle
1122 * TOP. It's pretty harmless because fetchall guarantees that any
1123 * message dropped by an interrupted RETR will be picked up on the
1124 * next poll of the site.
1126 * We take advantage here of the fact that, according to all the
1127 * POP RFCs, "if the number of lines requested by the POP3 client
1128 * is greater than than the number of lines in the body, then the
1129 * POP3 server sends the entire message.").
1131 * The line count passed (99999999) is the maximum value CompuServe will
1132 * accept; it's much lower than the natural value 2147483646 (the maximum
1133 * twos-complement signed 32-bit integer minus 1) */
1135 gen_send(sock, "RETR %d", number);
1137 gen_send(sock, "TOP %d 99999999", number);
1138 if ((ok = pop3_ok(sock, buf)) != 0)
1141 *lenp = -1; /* we got sizes from the LIST response */
1146 static void mark_uid_seen(struct query *ctl, int number)
1147 /* Tell the UID code we've seen this. */
1149 struct uid_db_record *rec;
1151 if ((rec = find_uid_by_num(&ctl->newsaved, number)))
1152 rec->status = UID_SEEN;
1153 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1154 * (say, due to socket error), the same mail will not be downloaded
1157 if ((rec = find_uid_by_num(&ctl->oldsaved, number)))
1158 rec->status = UID_SEEN;
1161 static int pop3_delete(int sock, struct query *ctl, int number)
1162 /* delete a given message */
1164 struct uid_db_record *rec;
1166 mark_uid_seen(ctl, number);
1167 /* actually, mark for deletion -- doesn't happen until QUIT time */
1168 ok = gen_transact(sock, "DELE %d", number);
1169 if (ok != PS_SUCCESS)
1172 rec = find_uid_by_num(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1173 rec->status = UID_DELETED;
1177 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1178 /* mark a given message as seen */
1181 mark_uid_seen(ctl, number);
1185 static int pop3_logout(int sock, struct query *ctl)
1186 /* send logout command */
1190 ok = gen_transact(sock, "QUIT");
1197 static const struct method pop3 =
1199 "POP3", /* Post Office Protocol v3 */
1200 "pop3", /* port for plain and TLS POP3 */
1201 "pop3s", /* port for SSL POP3 */
1202 FALSE, /* this is not a tagged protocol */
1203 TRUE, /* this uses a message delimiter */
1204 pop3_ok, /* parse command response */
1205 pop3_getauth, /* get authorization */
1206 pop3_getrange, /* query range of messages */
1207 pop3_getsizes, /* we can get a list of sizes */
1208 pop3_getpartialsizes, /* we can get the size of 1 mail */
1209 pop3_is_old, /* how do we tell a message is old? */
1210 pop3_fetch, /* request given message */
1211 NULL, /* no way to fetch body alone */
1212 NULL, /* no message trailer */
1213 pop3_delete, /* how to delete a message */
1214 pop3_mark_seen, /* how to mark a message as seen */
1215 NULL, /* no action at end of mailbox */
1216 pop3_logout, /* log out, we're done */
1217 FALSE, /* no, we can't re-poll */
1220 int doPOP3 (struct query *ctl)
1221 /* retrieve messages using POP3 */
1224 if (ctl->mailboxes->id) {
1225 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1230 return(do_protocol(ctl, &pop3));
1232 #endif /* POP3_ENABLE */
1234 /* pop3.c ends here */