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"
29 #endif /* OPIE_ENABLE */
31 /* global variables: please reinitialize them explicitly for proper
32 * working in daemon mode */
34 /* TODO: session variables to be initialized before server greeting */
36 static char lastok[POPBUFSIZE+1];
37 #endif /* OPIE_ENABLE */
39 /* session variables initialized in capa_probe() or pop3_getauth() */
40 flag done_capa = FALSE;
42 flag has_gssapi = FALSE;
43 #endif /* defined(GSSAPI) */
44 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
45 flag has_kerberos = FALSE;
46 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
47 static flag has_cram = FALSE;
50 #endif /* OPIE_ENABLE */
52 flag has_ntlm = FALSE;
53 #endif /* NTLM_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 char msgbuf[POPBUFSIZE+1];
87 gen_send(sock, msn_instead ? "AUTH MSN" : "AUTH NTLM");
89 if ((result = ntlm_helper(sock, ctl, "POP3")))
92 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
95 if (strstr (msgbuf, "OK"))
103 #define DOTLINE(s) (s[0] == '.' && (s[1]=='\r'||s[1]=='\n'||s[1]=='\0'))
105 static int pop3_ok (int sock, char *argbuf)
106 /* parse command response */
109 char buf [POPBUFSIZE+1];
112 if ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
114 if (*bufp == '+' || *bufp == '-')
119 while (isalpha((unsigned char)*bufp))
125 if (strcmp(buf,"+OK") == 0)
128 strcpy(lastok, bufp);
129 #endif /* OPIE_ENABLE */
132 else if (strncmp(buf,"-ERR", 4) == 0)
134 if (stage == STAGE_FETCH)
136 else if (stage > STAGE_GETAUTH)
139 * We're checking for "lock busy", "unable to lock",
140 * "already locked", "wait a few minutes" etc. here.
141 * This indicates that we have to wait for the server to
142 * unwedge itself before we can poll again.
144 * PS_LOCKBUSY check empirically verified with two recent
145 * versions of the Berkeley popper; QPOP (version 2.2) and
146 * QUALCOMM Pop server derived from UCB (version 2.1.4-R3)
147 * These are caught by the case-indifferent "lock" check.
148 * The "wait" catches "mail storage services unavailable,
149 * wait a few minutes and try again" on the InterMail server.
151 * If these aren't picked up on correctly, fetchmail will
152 * think there is an authentication failure and wedge the
153 * connection in order to prevent futile polls.
157 else if (strstr(bufp,"lock")
158 || strstr(bufp,"Lock")
159 || strstr(bufp,"LOCK")
160 || strstr(bufp,"wait")
161 /* these are blessed by RFC 2449 */
162 || strstr(bufp,"[IN-USE]")||strstr(bufp,"[LOGIN-DELAY]"))
164 else if ((strstr(bufp,"Service")
165 || strstr(bufp,"service"))
166 && (strstr(bufp,"unavailable")))
171 * We always want to pass the user lock-busy messages, because
172 * they're red flags. Other stuff (like AUTH failures on non-
173 * RFC1734 servers) only if we're debugging.
175 if (*bufp && (ok == PS_LOCKBUSY || outlevel >= O_MONITOR))
176 report(stderr, "%s\n", bufp);
181 #if POPBUFSIZE > MSGBUFSIZE
182 #error "POPBUFSIZE must not be larger than MSGBUFSIZE"
193 static int capa_probe(int sock)
194 /* probe the capabilities of the remote server */
203 #endif /* defined(GSSAPI) */
204 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
205 has_kerberos = FALSE;
206 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
210 #endif /* OPIE_ENABLE */
213 #endif /* NTLM_ENABLE */
215 ok = gen_transact(sock, "CAPA");
216 if (ok == PS_SUCCESS)
220 /* determine what authentication methods we have available */
221 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
227 if (strstr(buffer, "STLS"))
229 #endif /* SSL_ENABLE */
232 if (strstr(buffer, "GSSAPI"))
234 #endif /* defined(GSSAPI) */
236 #if defined(KERBEROS_V4)
237 if (strstr(buffer, "KERBEROS_V4"))
239 #endif /* defined(KERBEROS_V4) */
242 if (strstr(buffer, "X-OTP"))
244 #endif /* OPIE_ENABLE */
247 if (strstr(buffer, "NTLM"))
249 #endif /* NTLM_ENABLE */
251 if (strstr(buffer, "CRAM-MD5"))
259 static void set_peek_capable(struct query *ctl)
261 /* we're peek-capable means that the use of TOP is enabled,
262 * see pop3_fetch for details - short story, we can use TOP if
263 * we have a means of reliably tracking which mail we need to
264 * refetch should the connection abort in the middle.
265 * fetchall forces RETR, as does keep without UIDL */
266 peek_capable = !ctl->fetchall && (!ctl->keep || ctl->server.uidl);
269 static int pop3_getauth(int sock, struct query *ctl, char *greeting)
270 /* apply for connection authorization */
277 #endif /* OPIE_ENABLE */
279 flag connection_may_have_tls_errors = FALSE;
280 #endif /* SSL_ENABLE */
285 #endif /* defined(GSSAPI) */
286 #if defined(KERBEROS_V4) || defined(KERBEROS_V5)
287 has_kerberos = FALSE;
288 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
292 #endif /* OPIE_ENABLE */
295 #endif /* SSL_ENABLE */
297 /* Set this up before authentication quits early. */
298 set_peek_capable(ctl);
300 /* Hack: allow user to force RETR. */
301 if (peek_capable && getenv("FETCHMAIL_POP3_FORCE_RETR")) {
306 * The "Maillennium POP3/PROXY server" deliberately truncates
307 * TOP replies after c. 64 or 80 kByte (we have varying reports), so
308 * disable TOP. Comcast once spewed marketing babble to the extent
309 * of protecting Outlook -- pretty overzealous to break a protocol
310 * for that that Microsoft could have read, too. Comcast aren't
311 * alone in using this software though.
312 * <http://lists.ccil.org/pipermail/fetchmail-friends/2004-April/008523.html>
313 * (Thanks to Ed Wilts for reminding me of that.)
315 * The warning is printed once per server, until fetchmail exits.
316 * It will be suppressed when --fetchall or other circumstances make
317 * us use RETR anyhow.
321 if (peek_capable && strstr(greeting, "Maillennium POP3/PROXY server")) {
322 if ((ctl->server.workarounds & WKA_TOP) == 0) {
323 report(stdout, GT_("Warning: \"Maillennium POP3/PROXY server\" found, using RETR command instead of TOP.\n"));
324 ctl->server.workarounds |= WKA_TOP;
328 if (ctl->server.authenticate == A_SSH) {
334 * This needs to catch both demon.co.uk and demon.net.
335 * If we see either, and we're in multidrop mode, try to use
336 * the SDPS *ENV extension.
338 if (!(ctl->server.sdps) && MULTIDROP(ctl) && strstr(greeting, "demon."))
339 ctl->server.sdps = TRUE;
340 #endif /* SDPS_ENABLE */
342 switch (ctl->server.protocol) {
345 /* XXX FIXME: AUTH probing (RFC1734) should become global */
346 /* CompuServe POP3 Servers as of 990730 want AUTH first for RPA */
347 if (strstr(ctl->remotename, "@compuserve.com"))
349 /* AUTH command should return a list of available mechanisms */
350 if (gen_transact(sock, "AUTH") == 0)
353 flag has_rpa = FALSE;
355 while ((ok = gen_recv(sock, buffer, sizeof(buffer))) == 0)
359 if (strncasecmp(buffer, "rpa", 3) == 0)
362 if (has_rpa && !POP3_auth_rpa(ctl->remotename,
363 ctl->password, sock))
369 #endif /* RPA_ENABLE */
372 * CAPA command may return a list including available
373 * authentication mechanisms and STLS capability.
375 * If it doesn't, no harm done, we just fall back to a plain
376 * login -- if the user allows it.
378 * Note that this code latches the server's authentication type,
379 * so that in daemon mode the CAPA check only needs to be done
380 * once at start of run.
382 * If CAPA fails, then force the authentication method to
383 * PASSWORD, switch off opportunistic and repoll immediately.
384 * If TLS is mandatory, fail up front.
386 if ((ctl->server.authenticate == A_ANY) ||
387 (ctl->server.authenticate == A_GSSAPI) ||
388 (ctl->server.authenticate == A_KERBEROS_V4) ||
389 (ctl->server.authenticate == A_KERBEROS_V5) ||
390 (ctl->server.authenticate == A_OTP) ||
391 (ctl->server.authenticate == A_CRAM_MD5) ||
394 if ((ok = capa_probe(sock)) != PS_SUCCESS)
395 /* we are in STAGE_GETAUTH => failure is PS_AUTHFAIL! */
396 if (ok == PS_AUTHFAIL ||
397 /* Some servers directly close the socket. However, if we
398 * have already authenticated before, then a previous CAPA
399 * must have succeeded. In that case, treat this as a
400 * genuine socket error and do not change the auth method.
402 (ok == PS_SOCKET && !ctl->wehaveauthed))
406 /* fail with mandatory STLS without repoll */
407 report(stderr, GT_("TLS is mandatory for this session, but server refused CAPA command.\n"));
408 report(stderr, GT_("The CAPA command is however necessary for TLS.\n"));
410 } else if (maybe_tls(ctl)) {
411 /* defeat opportunistic STLS */
412 xfree(ctl->sslproto);
413 ctl->sslproto = xstrdup("");
416 /* If strong authentication was opportunistic, retry without, else fail. */
417 switch (ctl->server.authenticate) {
419 ctl->server.authenticate = A_PASSWORD;
421 case A_PASSWORD: /* this should only happen with TLS enabled */
430 if (maybe_tls(ctl)) {
433 commonname = ctl->server.pollname;
435 commonname = ctl->server.via;
436 if (ctl->sslcommonname)
437 commonname = ctl->sslcommonname;
440 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
442 /* Use "tls1" rather than ctl->sslproto because tls1 is the only
443 * protocol that will work with STARTTLS. Don't need to worry
444 * whether TLS is mandatory or opportunistic unless SSLOpen() fails
446 if (gen_transact(sock, "STLS") == PS_SUCCESS
447 && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
448 ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
449 ctl->server.pollname, &ctl->remotename) != -1)
452 * RFC 2595 says this:
454 * "Once TLS has been started, the client MUST discard cached
455 * information about server capabilities and SHOULD re-issue the
456 * CAPABILITY command. This is necessary to protect against
457 * man-in-the-middle attacks which alter the capabilities list prior
458 * to STARTTLS. The server MAY advertise different capabilities
461 * Now that we're confident in our TLS connection we can
462 * guarantee a secure capability re-probe.
465 ok = capa_probe(sock);
466 if (ok != PS_SUCCESS) {
469 if (outlevel >= O_VERBOSE)
471 report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
473 } else if (must_tls(ctl)) {
474 /* Config required TLS but we couldn't guarantee it, so we must
476 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
479 /* We don't know whether the connection is usable, and there's
480 * no command we can reasonably issue to test it (NOOP isn't
481 * allowed til post-authentication), so leave it in an unknown
482 * state, mark it as such, and check more carefully if things
483 * go wrong when we try to authenticate. */
484 connection_may_have_tls_errors = TRUE;
485 if (outlevel >= O_VERBOSE)
487 report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue.\n"), commonname);
492 #endif /* SSL_ENABLE */
495 * OK, we have an authentication type now.
497 #if defined(KERBEROS_V4)
499 * Servers doing KPOP have to go through a dummy login sequence
500 * rather than doing SASL.
503 ctl->server.service && (strcmp(ctl->server.service, KPOP_PORT)!=0)
504 && (ctl->server.authenticate == A_KERBEROS_V4
505 || ctl->server.authenticate == A_KERBEROS_V5
506 || ctl->server.authenticate == A_ANY))
508 ok = do_rfc1731(sock, "AUTH", ctl->server.truename);
509 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
512 #endif /* defined(KERBEROS_V4) || defined(KERBEROS_V5) */
516 (ctl->server.authenticate == A_GSSAPI ||
517 (ctl->server.authenticate == A_ANY
518 && check_gss_creds("pop", ctl->server.truename) == PS_SUCCESS)))
520 ok = do_gssauth(sock,"AUTH","pop",ctl->server.truename,ctl->remotename);
521 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
524 #endif /* defined(GSSAPI) */
528 (ctl->server.authenticate == A_OTP ||
529 ctl->server.authenticate == A_ANY))
531 ok = do_otp(sock, "AUTH", ctl);
532 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
535 #endif /* OPIE_ENABLE */
538 /* MSN servers require the use of NTLM (MSN) authentication */
539 if (!strcasecmp(ctl->server.pollname, "pop3.email.msn.com") ||
540 ctl->server.authenticate == A_MSN)
541 return (do_pop3_ntlm(sock, ctl, 1) == 0) ? PS_SUCCESS : PS_AUTHFAIL;
542 if (ctl->server.authenticate == A_NTLM || (has_ntlm && ctl->server.authenticate == A_ANY)) {
543 ok = do_pop3_ntlm(sock, ctl, 0);
544 if (ok == 0 || ctl->server.authenticate != A_ANY)
548 if (ctl->server.authenticate == A_NTLM || ctl->server.authenticate == A_MSN)
551 GT_("Required NTLM capability not compiled into fetchmail\n"));
555 if (ctl->server.authenticate == A_CRAM_MD5 ||
556 (has_cram && ctl->server.authenticate == A_ANY))
558 ok = do_cram_md5(sock, "AUTH", ctl, NULL);
559 if (ok == PS_SUCCESS || ctl->server.authenticate != A_ANY)
563 /* ordinary validation, no one-time password or RPA */
564 if ((ok = gen_transact(sock, "USER %s", ctl->remotename)))
568 /* see RFC1938: A One-Time Password System */
569 if ((challenge = strstr(lastok, "otp-"))) {
570 char response[OPIE_RESPONSE_MAX+1];
572 char *n = xstrdup("");
574 i = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? n : ctl->password, response);
576 if ((i == -2) && !run.poll_interval) {
577 char secret[OPIE_SECRET_MAX+1];
578 fprintf(stderr, GT_("Secret pass phrase: "));
579 if (opiereadpass(secret, sizeof(secret), 0))
580 i = opiegenerator(challenge, secret, response);
581 memset(secret, 0, sizeof(secret));
589 ok = gen_transact(sock, "PASS %s", response);
592 #endif /* OPIE_ENABLE */
594 /* KPOP uses out-of-band authentication and does not check what
595 * we send here, so send some random fixed string, to avoid
596 * users switching *to* KPOP accidentally revealing their
598 if ((ctl->server.authenticate == A_ANY
599 || ctl->server.authenticate == A_KERBEROS_V4
600 || ctl->server.authenticate == A_KERBEROS_V5)
601 && (ctl->server.service != NULL
602 && strcmp(ctl->server.service, KPOP_PORT) == 0))
604 ok = gen_transact(sock, "PASS krb_ticket");
608 /* check if we are actually allowed to send the password */
609 if (ctl->server.authenticate == A_ANY
610 || ctl->server.authenticate == A_PASSWORD) {
611 strlcpy(shroud, ctl->password, sizeof(shroud));
612 ok = gen_transact(sock, "PASS %s", ctl->password);
614 report(stderr, GT_("We've run out of allowed authenticators and cannot continue.\n"));
617 memset(shroud, 0x55, sizeof(shroud));
622 /* build MD5 digest from greeting timestamp + password */
623 /* find start of timestamp */
624 for (start = greeting; *start != 0 && *start != '<'; start++)
628 GT_("Required APOP timestamp not found in greeting\n"));
632 /* find end of timestamp */
633 for (end = start; *end != 0 && *end != '>'; end++)
635 if (*end == 0 || end == start + 1) {
637 GT_("Timestamp syntax error in greeting\n"));
643 /* SECURITY: 2007-03-17
644 * Strictly validating the presented challenge for RFC-822
645 * conformity (it must be a msg-id in terms of that standard) is
646 * supposed to make attacks against the MD5 implementation
649 * [1] "Security vulnerability in APOP authentication",
650 * Gaëtan Leurent, fetchmail-devel, 2007-03-17 */
651 if (!rfc822_valid_msgid((unsigned char *)start)) {
653 GT_("Invalid APOP timestamp.\n"));
657 /* copy timestamp and password into digestion buffer */
658 msg = (char *)xmalloc((end-start+1) + strlen(ctl->password) + 1);
660 strcat(msg,ctl->password);
661 strcpy((char *)ctl->digest, MD5Digest((unsigned char *)msg));
664 ok = gen_transact(sock, "APOP %s %s", ctl->remotename, (char *)ctl->digest);
668 if ((ok = gen_transact(sock,"USER %s", ctl->remotename)) == 0) {
669 strlcpy(shroud, ctl->password, sizeof(shroud));
670 ok = gen_transact(sock, "RPOP %s", ctl->password);
671 memset(shroud, 0x55, sizeof(shroud));
677 report(stderr, GT_("Undefined protocol request in POP3_auth\n"));
682 /* this is for servers which claim to support TLS, but actually
684 if (connection_may_have_tls_errors
685 && (ok == PS_SOCKET || ok == PS_PROTOCOL))
687 xfree(ctl->sslproto);
688 ctl->sslproto = xstrdup("");
689 /* repoll immediately without TLS */
696 /* maybe we detected a lock-busy condition? */
697 if (ok == PS_LOCKBUSY)
698 report(stderr, GT_("lock busy! Is another session active?\n"));
703 /* Disable the sleep. Based on patch by Brian Candler 2004-04-19/2004-11-08,
704 * accepted by Matthias Andree.
706 * Rationale: the server must have locked the spool before returning +OK;
707 * this sleep just wastes time and hence, for modem and GSM CSD users, money. */
710 * Empirical experience shows some server/OS combinations
711 * may need a brief pause even after any lockfiles on the
712 * server are released, to give the server time to finish
713 * copying back very large mailfolders from the temp-file...
714 * this is only ever an issue with extremely large mailboxes.
716 sleep(3); /* to be _really_ safe, probably need sleep(5)! */
723 /* cut off C string at first POSIX space */
724 static void trim(char *s) {
725 s += strcspn(s, POSIX_space);
729 /** Parse the UID response (leading +OK must have been
730 * stripped off) in buf, store the number in gotnum, and store the ID
731 * into the caller-provided buffer "id" of size "idsize".
732 * Returns PS_SUCCESS or PS_PROTOCOL for failure. */
733 static int parseuid(const char *buf, unsigned long *gotnum, char *id, size_t idsize)
738 /* skip leading blanks ourselves */
740 i += strspn(i, POSIX_space);
742 *gotnum = strtoul(i, &j, 10);
743 if (j == i || !*j || errno || NULL == strchr(POSIX_space, *j)) {
744 report(stderr, GT_("Cannot handle UIDL response from upstream server.\n"));
747 j += strspn(j, POSIX_space);
748 strlcpy(id, j, idsize);
753 /** request UIDL for single message \a num and stuff the result into the
754 * buffer \a id which can hold \a idsize bytes */
755 static int pop3_getuidl(int sock, int num, char *id /** output */, size_t idsize)
758 char buf [POPBUFSIZE+1];
759 unsigned long gotnum;
761 gen_send(sock, "UIDL %d", num);
762 if ((ok = pop3_ok(sock, buf)) != 0)
764 if ((ok = parseuid(buf, &gotnum, id, idsize)))
766 if (gotnum != (unsigned long)num) {
767 report(stderr, GT_("Server responded with UID for wrong message.\n"));
773 static int pop3_fastuidl( int sock, struct query *ctl, unsigned int count, int *newp)
776 unsigned int first_nr, last_nr, try_nr;
778 struct idlist *savep = NULL; /** pointer to cache save_str result, speeds up saves */
782 while (first_nr < last_nr - 1)
786 try_nr = (first_nr + last_nr) / 2;
787 if ((ok = pop3_getuidl(sock, try_nr, id, sizeof(id))) != 0)
789 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE)))
791 flag mark = newl->val.status.mark;
792 if (mark == UID_DELETED || mark == UID_EXPUNGED)
794 if (outlevel >= O_VERBOSE)
795 report(stderr, GT_("id=%s (num=%u) was deleted, but is still present!\n"), id, try_nr);
796 /* just mark it as seen now! */
797 newl->val.status.mark = mark = UID_SEEN;
800 /* narrow the search region! */
801 if (mark == UID_UNSEEN)
803 if (outlevel >= O_DEBUG)
804 report(stdout, GT_("%u is unseen\n"), try_nr);
810 /* save the number */
811 newl->val.status.num = try_nr;
815 if (outlevel >= O_DEBUG)
816 report(stdout, GT_("%u is unseen\n"), try_nr);
820 savep = save_str(savep ? &savep : &ctl->oldsaved, id, UID_UNSEEN);
821 savep->val.status.num = try_nr;
824 if (outlevel >= O_DEBUG && last_nr <= count)
825 report(stdout, GT_("%u is first unseen\n"), last_nr);
828 *newp = count - first_nr;
833 static int pop3_getrange(int sock,
836 int *countp, int *newp, int *bytes)
837 /* get range of messages to be fetched */
840 char buf [POPBUFSIZE+1];
843 /* Ensure that the new list is properly empty */
844 ctl->newsaved = (struct idlist *)NULL;
847 /* Alain Knaff suggests this, but it's not RFC standard */
849 if ((ok = gen_transact(sock, "MBOX %s", folder)))
853 /* get the total message count */
854 gen_send(sock, "STAT");
855 ok = pop3_ok(sock, buf);
859 asgn = sscanf(buf,"%d %d", countp, bytes);
866 * Newer, RFC-1725/1939-conformant POP servers may not have the LAST
867 * command. We work as hard as possible to hide this, but it makes
868 * counting new messages intrinsically quadratic in the worst case.
872 /* if there are messages, and UIDL is desired, use UIDL
873 * also use UIDL if fetchall is unset */
874 if (*countp > 0 && (!ctl->fetchall || ctl->server.uidl))
879 /* should we do fast uidl this time? */
880 fastuidl = ctl->fastuidl;
881 if (*countp > 7 && /* linear search is better if there are few mails! */
882 !ctl->fetchall && /* with fetchall, all uids are required */
883 !ctl->flush && /* with flush, it is safer to disable fastuidl */
884 NUM_NONZERO (fastuidl))
889 dofastuidl = ctl->fastuidlcount != 0;
894 if (!ctl->server.uidl) {
895 gen_send(sock, "LAST");
896 ok = pop3_ok(sock, buf);
902 /* scan LAST reply */
903 if (sscanf(buf, "%d", &last) == 0)
905 report(stderr, GT_("protocol error\n"));
908 *newp = (*countp - last);
914 return(pop3_fastuidl( sock, ctl, *countp, newp));
915 /* grab the mailbox's UID list */
916 if (gen_transact(sock, "UIDL") != 0)
918 report(stderr, GT_("protocol error while fetching UIDLs\n"));
923 /* UIDL worked - parse reply */
925 struct idlist *newl = NULL;
928 while (gen_recv(sock, buf, sizeof(buf)) == PS_SUCCESS)
933 if (parseuid(buf, &unum, id, sizeof(id)) == PS_SUCCESS)
937 newl = save_str(newl ? &newl : &ctl->newsaved, id, UID_UNSEEN);
938 newl->val.status.num = unum;
940 if ((old = str_in_list(&ctl->oldsaved, id, FALSE)))
942 flag mark = old->val.status.mark;
943 if (mark == UID_DELETED || mark == UID_EXPUNGED)
945 /* XXX FIXME: switch 3 occurrences from
946 * (int)unum or (unsigned int)unum to
947 * remove the cast and use %lu - not now
948 * though, time for new release */
949 if (outlevel >= O_VERBOSE)
950 report(stderr, GT_("id=%s (num=%d) was deleted, but is still present!\n"), id, (int)unum);
951 /* just mark it as seen now! */
952 old->val.status.mark = mark = UID_SEEN;
954 newl->val.status.mark = mark;
955 if (mark == UID_UNSEEN)
958 if (outlevel >= O_DEBUG)
959 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
965 if (outlevel >= O_DEBUG)
966 report(stdout, GT_("%u is unseen\n"), (unsigned int)unum);
967 /* add it to oldsaved also! In case, we do not
968 * swap the lists (say, due to socket error),
969 * the same mail will not be downloaded again.
971 old = save_str(&ctl->oldsaved, id, UID_UNSEEN);
973 /* save the number */
974 old->val.status.num = unum;
977 } /* multi-line loop for UIDL reply */
985 static int pop3_getpartialsizes(int sock, int first, int last, int *sizes)
986 /* capture the size of message #first */
989 char buf [POPBUFSIZE+1];
992 for (i = first; i <= last; i++) {
993 gen_send(sock, "LIST %d", i);
994 if ((ok = pop3_ok(sock, buf)) != 0)
996 if (sscanf(buf, "%d %u", &num, &size) == 2) {
998 sizes[i - first] = size;
1000 /* warn about possible attempt to induce buffer overrun
1002 * we expect server reply message number and requested
1003 * message number to match */
1004 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1010 static int pop3_getsizes(int sock, int count, int *sizes)
1011 /* capture the sizes of all messages */
1015 if ((ok = gen_transact(sock, "LIST")) != 0)
1019 char buf [POPBUFSIZE+1];
1021 while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0)
1023 unsigned int num, size;
1027 else if (sscanf(buf, "%u %u", &num, &size) == 2) {
1028 if (num > 0 && num <= (unsigned)count)
1029 sizes[num - 1] = size;
1031 /* warn about possible attempt to induce buffer overrun */
1032 report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n");
1040 static int pop3_is_old(int sock, struct query *ctl, int num)
1041 /* is the given message old? */
1043 struct idlist *newl;
1045 return (num <= last);
1046 else if (dofastuidl)
1053 /* in fast uidl, we manipulate the old list only! */
1055 if ((newl = id_find(&ctl->oldsaved, num)))
1057 /* we already have the id! */
1058 return(newl->val.status.mark != UID_UNSEEN);
1061 /* get the uidl first! */
1062 if (pop3_getuidl(sock, num, id, sizeof(id)) != PS_SUCCESS)
1065 if ((newl = str_in_list(&ctl->oldsaved, id, FALSE))) {
1066 /* we already have the id! */
1067 newl->val.status.num = num;
1068 return(newl->val.status.mark != UID_UNSEEN);
1072 newl = save_str(&ctl->oldsaved, id, UID_UNSEEN);
1073 newl->val.status.num = num;
1077 return ((newl = id_find(&ctl->newsaved, num)) != NULL &&
1078 newl->val.status.mark != UID_UNSEEN);
1083 * We could use this to fetch headers only as we do for IMAP. The trouble
1084 * is that there's no way to fetch the body only. So the following RETR
1085 * would have to re-fetch the header. Enough messages have longer headers
1086 * than bodies to make this a net loss.
1088 static int pop_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1089 /* request headers of nth message */
1092 char buf[POPBUFSIZE+1];
1094 gen_send(sock, "TOP %d 0", number);
1095 if ((ok = pop3_ok(sock, buf)) != 0)
1098 *lenp = -1; /* we got sizes from the LIST response */
1104 static int pop3_fetch(int sock, struct query *ctl, int number, int *lenp)
1105 /* request nth message */
1108 char buf[POPBUFSIZE+1];
1112 * See http://www.demon.net/helpdesk/producthelp/mail/sdps-tech.html/
1113 * for a description of what we're parsing here.
1114 * -- updated 2006-02-22
1116 if (ctl->server.sdps)
1120 sdps_envfrom = (char *)NULL;
1121 sdps_envto = (char *)NULL;
1122 gen_send(sock, "*ENV %d", number);
1124 if (gen_recv(sock, buf, sizeof(buf)))
1129 switch (linecount) {
1131 /* No need to wrap envelope from address */
1132 /* FIXME: some parts of fetchmail don't handle null
1133 * envelope senders, so use <> to mark null sender
1134 * as a workaround. */
1135 if (strspn(buf, " \t") == strlen(buf))
1137 sdps_envfrom = (char *)xmalloc(strlen(buf)+1);
1138 strcpy(sdps_envfrom,buf);
1141 /* Wrap address with To: <> so nxtaddr() likes it */
1142 sdps_envto = (char *)xmalloc(strlen(buf)+7);
1143 sprintf(sdps_envto,"To: <%s>",buf);
1147 (!(buf[0] == '.' && (buf[1] == '\r' || buf[1] == '\n' || buf[1] == '\0')));
1151 #endif /* SDPS_ENABLE */
1154 * Though the POP RFCs don't document this fact, on almost every
1155 * POP3 server I know of messages are marked "seen" only at the
1156 * time the OK response to a RETR is issued.
1158 * This means we can use TOP to fetch the message without setting its
1159 * seen flag. This is good! It means that if the protocol exchange
1160 * craps out during the message, it will still be marked `unseen' on
1161 * the server. (Exception: in early 1999 SpryNet's POP3 servers were
1162 * reported to mark messages seen on a TOP fetch.)
1164 * However...*don't* do this if we're using keep to suppress deletion!
1165 * In that case, marking the seen flag is the only way to prevent the
1166 * message from being re-fetched on subsequent runs.
1168 * Also use RETR (that means no TOP, no peek) if fetchall is on.
1169 * This gives us a workaround for servers like usa.net's that bungle
1170 * TOP. It's pretty harmless because fetchall guarantees that any
1171 * message dropped by an interrupted RETR will be picked up on the
1172 * next poll of the site.
1174 * We take advantage here of the fact that, according to all the
1175 * POP RFCs, "if the number of lines requested by the POP3 client
1176 * is greater than than the number of lines in the body, then the
1177 * POP3 server sends the entire message.").
1179 * The line count passed (99999999) is the maximum value CompuServe will
1180 * accept; it's much lower than the natural value 2147483646 (the maximum
1181 * twos-complement signed 32-bit integer minus 1) */
1183 gen_send(sock, "RETR %d", number);
1185 gen_send(sock, "TOP %d 99999999", number);
1186 if ((ok = pop3_ok(sock, buf)) != 0)
1189 *lenp = -1; /* we got sizes from the LIST response */
1194 static void mark_uid_seen(struct query *ctl, int number)
1195 /* Tell the UID code we've seen this. */
1199 if ((sdp = id_find(&ctl->newsaved, number)))
1200 sdp->val.status.mark = UID_SEEN;
1201 /* mark it as seen in oldsaved also! In case, we do not swap the lists
1202 * (say, due to socket error), the same mail will not be downloaded
1205 if ((sdp = id_find(&ctl->oldsaved, number)))
1206 sdp->val.status.mark = UID_SEEN;
1209 static int pop3_delete(int sock, struct query *ctl, int number)
1210 /* delete a given message */
1213 mark_uid_seen(ctl, number);
1214 /* actually, mark for deletion -- doesn't happen until QUIT time */
1215 ok = gen_transact(sock, "DELE %d", number);
1216 if (ok != PS_SUCCESS)
1218 delete_str(dofastuidl ? &ctl->oldsaved : &ctl->newsaved, number);
1222 static int pop3_mark_seen(int sock, struct query *ctl, int number)
1223 /* mark a given message as seen */
1226 mark_uid_seen(ctl, number);
1230 static int pop3_logout(int sock, struct query *ctl)
1231 /* send logout command */
1237 * We used to do this in case the server marks messages deleted when seen.
1238 * (Yes, this has been reported, in the MercuryP/NLM server.
1239 * It's even legal under RFC 1939 (section 8) as a site policy.)
1240 * It interacted badly with UIDL, though. Thomas Zajic wrote:
1241 * "Running 'fetchmail -F -v' and checking the logs, I found out
1242 * that fetchmail did in fact flush my mailbox properly, but sent
1243 * a RSET just before sending QUIT to log off. This caused the
1244 * POP3 server to undo/forget about the previous DELEs, resetting
1245 * my mailbox to its original (ie. unflushed) state. The
1246 * ~/.fetchids file did get flushed though, so the next time
1247 * fetchmail was run it saw all the old messages as new ones ..."
1250 gen_transact(sock, "RSET");
1251 #endif /* __UNUSED__ */
1253 ok = gen_transact(sock, "QUIT");
1260 static const struct method pop3 =
1262 "POP3", /* Post Office Protocol v3 */
1263 "pop3", /* port for plain and TLS POP3 */
1264 "pop3s", /* port for SSL POP3 */
1265 FALSE, /* this is not a tagged protocol */
1266 TRUE, /* this uses a message delimiter */
1267 pop3_ok, /* parse command response */
1268 pop3_getauth, /* get authorization */
1269 pop3_getrange, /* query range of messages */
1270 pop3_getsizes, /* we can get a list of sizes */
1271 pop3_getpartialsizes, /* we can get the size of 1 mail */
1272 pop3_is_old, /* how do we tell a message is old? */
1273 pop3_fetch, /* request given message */
1274 NULL, /* no way to fetch body alone */
1275 NULL, /* no message trailer */
1276 pop3_delete, /* how to delete a message */
1277 pop3_mark_seen, /* how to mark a message as seen */
1278 NULL, /* no action at end of mailbox */
1279 pop3_logout, /* log out, we're done */
1280 FALSE, /* no, we can't re-poll */
1283 int doPOP3 (struct query *ctl)
1284 /* retrieve messages using POP3 */
1287 if (ctl->mailboxes->id) {
1288 fprintf(stderr,GT_("Option --folder is not supported with POP3\n"));
1293 return(do_protocol(ctl, &pop3));
1295 #endif /* POP3_ENABLE */
1297 /* pop3.c ends here */